List of usage examples for com.rabbitmq.client Connection close
@Override void close() throws IOException;
From source file:com.qt.core.util.MqConnectionUtil.java
License:Open Source License
public synchronized void closeConn(String key) { Connection conn = getConnection(key); if (conn != null && conn.isOpen()) { try {//from ww w. j av a 2s . co m connectionMap.remove(key); conn.close(); conn = null; } catch (IOException e) { logger.error(null, e); } } }
From source file:com.service.OperationFacadeREST.java
@POST @Override// w ww . j a v a 2 s.c om @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public void create(Operation entity) { if (!entity.getState().equals("waiting")) { super.create(entity); return; } if (entity.getOperationType())//venda { ArrayList<ClientStock> l = new ArrayList<>(getEntityManager() .find(Client.class, entity.getFkOwnerId().getClientId()).getClientStockCollection()); Boolean fail = false; for (int i = 0; i < l.size(); i++) { if (l.get(i).getStock().equals(entity.getFkStockId())) { if (l.get(i).getQuantity() < entity.getQuantity()) return; l.get(i).setQuantity(l.get(i).getQuantity() - entity.getQuantity()); getEntityManager().persist(l.get(i)); entity.getFkOwnerId().setClientStockCollection(l); entity.setCreationDate(Date.from(Instant.now())); super.create(entity); } } if (fail) return; } else { entity.setCreationDate(Date.from(Instant.now())); if (entity.getFkStockId().getQuantity() > entity.getQuantity()) { System.out.println("yes"); super.create(entity); } else { return; } } try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello", false, false, false, null); System.out.println(super.findAll().get(super.findAll().size() - 1).getOperationId() + "," + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + "," + entity.getQuantity()); String message = super.findAll().get(super.findAll().size() - 1).getOperationId() + "," + entity.getFkOwnerId().getName() + "," + entity.getFkStockId().getName() + "," + entity.getQuantity(); channel.basicPublish("", "hello", null, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close(); } catch (IOException ex) { Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex); } catch (TimeoutException ex) { Logger.getLogger(ClientFacadeREST.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.shopwiki.roger.example.ExampleEventHandler.java
License:Apache License
public static void main(String[] args) throws Exception { MessageHandler<String> handler = new MessageHandler<String>() { @Override/*w w w. ja v a2s. c o m*/ public TypeReference<String> getMessageType() { return new TypeReference<String>() { }; } @Override public void handleMessage(String name) { System.out.println("Hello " + name + "!"); } }; // Create the exchange if it doesn't exist. { Connection conn = connector.getConnection(1); Channel channel = conn.createChannel(); channel.exchangeDeclare(route.exchange, "topic"); conn.close(); } boolean daemon = false; MessageWorker<String> worker = new MessageWorker<String>(connector, handler, route, daemon); worker.start(); }
From source file:com.shopwiki.roger.RabbitConnector.java
License:Apache License
/** * Close connection if it's not null./*from ww w. j a v a 2s. c o m*/ * Swallow IOExceptions. * @param conn */ public static void closeConnection(Connection conn) { if (conn == null) { return; } try { conn.close(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException(e); } }
From source file:com.sitewhere.protobuf.test.ActiveMQTests.java
License:Open Source License
@Test public void doRabbitMQTest() throws Exception { String exchangeName = "sitewhere"; String queueName = "SITEWHERE.IN"; String routingKey = "sitewhere"; ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://localhost:5672/SITEWHERE.IN"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); byte[] messageBodyBytes = generateEncodedMeasurementsMessage(); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); channel.close();// ww w .ja v a 2 s .co m connection.close(); }
From source file:com.sitewhere.sources.ActiveMQTests.java
License:Open Source License
@Test public void doRabbitMQTest() throws Exception { String exchangeName = "sitewhere"; String queueName = "sitewhere.input"; String routingKey = "sitewhere"; ConnectionFactory factory = new ConnectionFactory(); factory.setUri("amqp://localhost:5672"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); byte[] messageBodyBytes = EventsHelper.generateEncodedMeasurementsMessage(HARDWARE_ID); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); channel.close();/* ww w . ja v a 2s. c o m*/ connection.close(); }
From source file:com.siva.rabbitmq.AmqpMsgPublisher.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setUsername("admin"); factory.setPassword("welcome01"); factory.setPort(5672);//from w ww . j ava 2 s . c o m factory.setVirtualHost("/admin_vhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); String routingKey = "mqtt_topic.iot.admin_vhost"; String message = "Test Message from IoT"; channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes()); System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'"); connection.close(); }
From source file:com.trivago.mail.pigeon.daemon.Daemon.java
License:Apache License
/** * Main Daemon method containing the event loop. * * @param args command line args/*from w ww. j a v a2 s . c om*/ * @throws java.io.IOException */ public static void main(String[] args) throws IOException { Connection conn = null; Channel channel = null; try { conn = ConnectionPool.getConnection(); channel = conn.createChannel(); boolean autoAck = false; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(channelName, autoAck, consumer); MailFacade mailFacade = new MailFacade(); while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(); } catch (InterruptedException ie) { continue; } String jsonContent = new String(delivery.getBody()); MailTransport mailTransport = JSONParser.defaultJSONParser().parse(MailTransport.class, jsonContent); mailFacade.sendMail(mailTransport); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } finally { if (channel != null) { channel.close(); } if (conn != null) { conn.close(); } } }
From source file:com.UseCaseSimpleConsumer.java
License:Open Source License
public static void main(String[] argv) throws java.io.IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); try {/*from ww w .ja v a 2 s .c om*/ channel.exchangeDeclarePassive(EXCHANGE_NAME); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct"); } try { channel.queueDeclarePassive(ROUTE_KEY); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.queueDeclare(ROUTE_KEY, false, false, false, null); } channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY); String param = "IBM"; String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + " <m:order>\n" + " <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + " <m:quantity>" + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + " <m:symbol>" + param + "</m:symbol>\n" + " </m:order>\n" + "</m:placeOrder>"; channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY, new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes()); System.out.println(" [x] Sent '" + msg + "'"); channel.close(); connection.close(); }
From source file:com.vmware.bdd.utils.RabbitMQConsumer.java
License:Open Source License
/** * Receive and process each message until the listener indicating. A new * queue will be created when start and will be deleted when stopping * receiving message./*w w w . j av a2 s . co m*/ * * FIXME Is it a best practice to create one queue for one task? Or we should * create one thread to handle all messages? * * @param listener * message processor callback * @throws IOException */ public void processMessage(MessageListener listener) throws IOException { ConnectionFactory factory = new ConnectionFactory(); if (username != null && !username.equals("")) { factory.setUsername(username); factory.setPassword(password); } factory.setVirtualHost("/"); factory.setHost(host); factory.setPort(port); Connection conn = factory.newConnection(); Channel channel = conn.createChannel(); /** * make exchange and queue non-durable */ channel.exchangeDeclare(exchangeName, "direct", true); if (!getQueue) { channel.queueDeclare(queueName, false, true, true, null); } else { queueName = channel.queueDeclare().getQueue(); } channel.queueBind(queueName, exchangeName, routingKey); boolean noAck = false; QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, noAck, consumer); while (true) { QueueingConsumer.Delivery delivery; try { delivery = consumer.nextDelivery(mqRecvTimeoutMs); } catch (InterruptedException e) { logger.warn("message consumer interrupted", e); continue; } if (delivery == null) { logger.debug("timeout, no message received"); if (stopping && new Date().after(mqExpireTime)) { logger.error("stop receiving messages without normal termination"); break; } continue; } String message = new String(delivery.getBody()); if (graceStopping) { extendExpirationTime(); } logger.info("message received: " + message); try { if (!listener.onMessage(message)) { logger.info("stop receiving messages normally"); break; } } catch (Throwable t) { logger.error("calling message listener failed", t); // discard and continue in non-debug mode AuAssert.unreachable(); } channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } try { channel.queueDelete(queueName); } catch (AlreadyClosedException e) { logger.error("failed to delete queue: " + queueName, e); } try { channel.close(); } catch (AlreadyClosedException e) { logger.error("failed to close channel, queue: " + queueName, e); } try { conn.close(); } catch (AlreadyClosedException e) { logger.error("failed to close connection, queue: " + queueName, e); } }