List of usage examples for com.rabbitmq.client Channel queueBind
Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;
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();/*from w w w . j a v a 2 s . c o m*/ connection.close(); }
From source file:com.trivago.mail.pigeon.web.data.process.QueueNewsletter.java
License:Apache License
private void queueNewsletter(Mail mail, Sender sender, Recipient recipient, Campaign campaign) { Connection conn = ConnectionPool.getConnection(); Channel channel = null; MailTransport transport = templateProcessor.processMail(mail, recipient, sender, campaign); if (transport == null) { log.warn(//from ww w. ja va 2 s .c o m "Template processor returned null instead of a mail transport object. This is probably a bug!"); return; } if (transport.shouldAbortSending() && !transport.shouldEnforceSending()) { log.info("Skipped mail to " + transport.getTo() + " because transport aborted sending."); return; } String json = JSON.defaultJSON().forValue(transport); try { channel = conn.createChannel(); channel.exchangeDeclare("mailpidgeon", "direct", true); channel.queueDeclare(channelName, true, false, false, null); channel.queueBind(channelName, "mailpidgeon", "mailpidgeon"); byte[] messageBodyBytes = json.getBytes(); channel.basicPublish("mailpidgeon", "mailpidgeon", null, messageBodyBytes); } catch (IOException e) { log.error(e); } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { log.error("Could not close channel", e); } } } }
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 w w w. j a v a2 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.UseCaseSimpleProducer.java
License:Open Source License
public static void main(String[] argv) throws java.io.IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); try {// w ww . j ava 2s . c o m channel.exchangeDeclarePassive(EXCHANGE_NAME); } catch (java.io.IOException e) { channel.exchangeDeclare(EXCHANGE_NAME, "direct"); } try { channel.queueDeclarePassive(QUEUE_NAME); } catch (java.io.IOException e) { channel.queueDeclare(QUEUE_NAME, false, false, false, null); } channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); } }
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 a 2s. c o 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); } }
From source file:com.vmware.vhadoop.vhm.rabbit.RabbitConnection.java
License:Open Source License
private synchronized String getQueueName() throws IOException { if (_queueName == null) { String exchangeName = _credentials.getExchangeName(); Channel channel = getChannel(); channel.exchangeDeclare(exchangeName, "direct", true, false, null); /* TODO: Externalize? */ _queueName = channel.queueDeclare().getQueue(); channel.queueBind(_queueName, exchangeName, _credentials.getRouteKeyCommand()); _log.fine("Created transient queue: " + _queueName); }/*from w w w. j a va 2 s . c o m*/ return _queueName; }
From source file:controllers.TargetController.java
License:Open Source License
/** * This method pushes a message onto a RabbitMQ queue for given target * using global settings from project configuration file. * * @param target The field URL of the target * @return/* ww w .jav a2 s . c o m*/ */ public static Result archive(Long id) { Target target = Target.findById(id); Logger.debug("archiveTarget() " + target); if (target != null) { if (!target.isInScopeAllOrInheritedWithoutLicense()) { return ok(infomessage.render("On-demand archiving is only supported for NPLD targets.")); } // Send the message: try { String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST); String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT); String queueName = Play.application().configuration().getString(Const.QUEUE_NAME); String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY); String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME); Logger.debug("archiveTarget() queue host: " + queueHost); Logger.debug("archiveTarget() queue port: " + queuePort); Logger.debug("archiveTarget() queue name: " + queueName); Logger.debug("archiveTarget() routing key: " + routingKey); Logger.debug("archiveTarget() exchange name: " + exchangeName); JsonNode jsonData = Json.toJson(target); String message = jsonData.toString(); Logger.debug("Crawl Now message: " + message); ConnectionFactory factory = new ConnectionFactory(); if (queueHost != null) { factory.setHost(queueHost); } if (queuePort != null) { factory.setPort(Integer.parseInt(queuePort)); } 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); BasicProperties.Builder propsBuilder = new BasicProperties.Builder(); propsBuilder.deliveryMode(2); channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes()); channel.close(); connection.close(); } catch (IOException e) { String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator."; User currentUser = User.findByEmail(request().username()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msgFullTrace = sw.toString(); Logger.error(msgFullTrace); if (currentUser.hasRole("sys_admin")) { msg = msgFullTrace; } return ok(infomessage.render(msg)); } catch (Exception e) { String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator."; User currentUser = User.findByEmail(request().username()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String msgFullTrace = sw.toString(); Logger.error(msgFullTrace); if (currentUser.hasRole("sys_admin")) { msg = msgFullTrace; } return ok(infomessage.render(msg)); } } else { Logger.debug("There was a problem sending the message. Target field for archiving is empty"); return ok(infomessage .render("There was a problem sending the message. Target field for archiving is empty")); } return ok(ukwalicenceresult.render()); }
From source file:controllerStuff.ControllerPublisher.java
private void attachControllerCallback(Controller controllerObject) { try {/*ww w. j a v a 2 s. c o m*/ Channel controllerCallbackChannel = connection.createChannel(); controllerCallbackChannel.exchangeDeclare(EXCHANGE_CONTOLLER_CMD, "topic"); String sensChName = controllerCallbackChannel.queueDeclare().getQueue(); controllerCallbackChannel.queueBind(sensChName, EXCHANGE_CONTOLLER_CMD, BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); System.out.println(BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); //Debug controllerCallbackChannel.basicConsume(sensChName, true, new DefaultConsumer(controllerCallbackChannel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { controllerObject.call(new String(body, "UTF-8")); } }); } catch (IOException ex) { Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:deck36.storm.plan9.RabbitMQDeclarator.java
License:Open Source License
@Override public void execute(Channel channel) { try {//from ww w.j a va 2s. co m channel.exchangeDeclare(exchange, // name "topic", // type true // durable? ); channel.queueDeclare(queue, // name true, // durable? false, // exclusive? false, // autoDelete null // Map(<String, Object> arguments ); channel.queueBind(queue, exchange, routingKey); } catch (IOException e) { throw new RuntimeException("Error executing rabbitmq declarations.", e); } }
From source file:dk.cphbusiness.group11.Translators.PoorBankWS.TranslatorPoorBankWS.java
public void run() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(RECEIVING_QUEUE, "fanout"); String queueName = channel.queueDeclare(RECEIVING_QUEUE, false, false, false, null).getQueue(); channel.queueBind(queueName, RECEIVING_QUEUE, ""); System.out.println("Waiting for messages on queue: " + RECEIVING_QUEUE); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (this.isRunning) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println("Received '" + message + "'"); this.parseAndProcessXmlMessage(message); }//from ww w . ja v a 2 s .c om }