List of usage examples for com.rabbitmq.client Channel queueBind
Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;
From source file:io.bootique.rabbitmq.client.channel.ChannelFactory.java
License:Apache License
/** * TODO: Comment what this method should do (and actually do) * Create channel and bind queue to exchange. *///from ww w.j av a 2 s .com public Channel openChannel(Connection connection, String exchangeName, String queueName, String routingKey) { try { Channel channel = connection.createChannel(); exchangeDeclare(channel, exchangeName); if (queueName == null) { queueName = channel.queueDeclare().getQueue(); } else { queueDeclare(channel, queueName); } channel.queueBind(queueName, exchangeName, routingKey); return channel; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:io.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java
License:Apache License
@Override public Firehose connect(StringInputRowParser firehoseParser) throws IOException { final StringInputRowParser stringParser = firehoseParser; ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory); Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries()) .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds())) .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds()))); String queue = config.getQueue(); String exchange = config.getExchange(); String routingKey = config.getRoutingKey(); boolean durable = config.isDurable(); boolean exclusive = config.isExclusive(); boolean autoDelete = config.isAutoDelete(); final Connection connection = Connections.create(lyraOptions, lyraConfig); connection.addShutdownListener(new ShutdownListener() { @Override//ww w .j a v a 2 s . co m public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Connection closed!"); } }); final Channel channel = connection.createChannel(); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchange, routingKey); channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Channel closed!"); } }); // We create a QueueingConsumer that will not auto-acknowledge messages since that // happens on commit(). final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); return new Firehose() { /** * Storing the latest delivery as a member variable should be safe since this will only be run * by a single thread. */ private Delivery delivery; /** * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to * and including this tag. See commit() for more detail. */ private long lastDeliveryTag; @Override public boolean hasMore() { delivery = null; try { // Wait for the next delivery. This will block until something is available. delivery = consumer.nextDelivery(); if (delivery != null) { lastDeliveryTag = delivery.getEnvelope().getDeliveryTag(); // If delivery is non-null, we report that there is something more to process. return true; } } catch (InterruptedException e) { // A little unclear on how we should handle this. // At any rate, we're in an unknown state now so let's log something and return false. log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen."); } // This means that delivery is null or we caught the exception above so we report that we have // nothing more to process. return false; } @Override public InputRow nextRow() { if (delivery == null) { //Just making sure. log.wtf("I have nothing in delivery. Method hasMore() should have returned false."); return null; } return stringParser.parse(StringUtils.fromUtf8(delivery.getBody())); } @Override public Runnable commit() { // This method will be called from the same thread that calls the other methods of // this Firehose. However, the returned Runnable will be called by a different thread. // // It should be (thread) safe to copy the lastDeliveryTag like we do below and then // acknowledge values up to and including that value. return new Runnable() { // Store (copy) the last delivery tag to "become" thread safe. final long deliveryTag = lastDeliveryTag; @Override public void run() { try { log.info("Acknowledging delivery of messages up to tag: " + deliveryTag); // Acknowledge all messages up to and including the stored delivery tag. channel.basicAck(deliveryTag, true); } catch (IOException e) { log.error(e, "Unable to acknowledge message reception to message queue."); } } }; } @Override public void close() throws IOException { log.info("Closing connection to RabbitMQ"); channel.close(); connection.close(); } }; }
From source file:io.druid.segment.realtime.firehose.RabbitMQFirehoseFactory.java
License:Open Source License
@Override public Firehose connect() throws IOException { String queue = config.getQueue(); String exchange = config.getExchange(); String routingKey = config.getRoutingKey(); boolean durable = config.isDurable(); boolean exclusive = config.isExclusive(); boolean autoDelete = config.isAutoDelete(); final Connection connection = connectionFactory.newConnection(); connection.addShutdownListener(new ShutdownListener() { @Override//from w ww.ja v a 2 s .com public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Connection closed!"); //FUTURE: we could try to re-establish the connection here. Not done in this version though. } }); final Channel channel = connection.createChannel(); channel.queueDeclare(queue, durable, exclusive, autoDelete, null); channel.queueBind(queue, exchange, routingKey); channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { log.warn(cause, "Channel closed!"); //FUTURE: we could try to re-establish the connection here. Not done in this version though. } }); // We create a QueueingConsumer that will not auto-acknowledge messages since that // happens on commit(). final QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queue, false, consumer); return new Firehose() { /** * Storing the latest delivery as a member variable should be safe since this will only be run * by a single thread. */ private QueueingConsumer.Delivery delivery; /** * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to * and including this tag. See commit() for more detail. */ private long lastDeliveryTag; @Override public boolean hasMore() { delivery = null; try { // Wait for the next delivery. This will block until something is available. delivery = consumer.nextDelivery(); if (delivery != null) { lastDeliveryTag = delivery.getEnvelope().getDeliveryTag(); // If delivery is non-null, we report that there is something more to process. return true; } } catch (InterruptedException e) { // A little unclear on how we should handle this. // At any rate, we're in an unknown state now so let's log something and return false. log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen."); } // This means that delivery is null or we caught the exception above so we report that we have // nothing more to process. return false; } @Override public InputRow nextRow() { if (delivery == null) { //Just making sure. log.wtf("I have nothing in delivery. Method hasMore() should have returned false."); return null; } return parser.parse(new String(delivery.getBody())); } @Override public Runnable commit() { // This method will be called from the same thread that calls the other methods of // this Firehose. However, the returned Runnable will be called by a different thread. // // It should be (thread) safe to copy the lastDeliveryTag like we do below and then // acknowledge values up to and including that value. return new Runnable() { // Store (copy) the last delivery tag to "become" thread safe. final long deliveryTag = lastDeliveryTag; @Override public void run() { try { log.info("Acknowledging delivery of messages up to tag: " + deliveryTag); // Acknowledge all messages up to and including the stored delivery tag. channel.basicAck(deliveryTag, true); } catch (IOException e) { log.error(e, "Unable to acknowledge message reception to message queue."); } } }; } @Override public void close() throws IOException { log.info("Closing connection to RabbitMQ"); channel.close(); connection.close(); } }; }
From source file:io.qdb.server.input.RabbitMQInputHandler.java
License:Apache License
protected void initChannel(Channel channel) throws IOException { channel.queueDeclare(queue, queueDurable, false, false, null); if (exchange != null) { channel.exchangeDeclare(exchange, exchangeType, exchangeDurable); channel.queueBind(queue, exchange, routingKey); }//from w w w. j ava 2s .co m }
From source file:io.qdb.server.output.RabbitMQOutputHandler.java
License:Apache License
protected void initChannel(Channel channel) throws IOException { channel.exchangeDeclare(exchange, exchangeType, exchangeDurable); if (queues != null) { for (int i = 0; i < queues.length; i++) { String q = queues[i]; channel.queueDeclare(q, queueDurable[i], false, false, null); channel.queueBind(q, exchange, ""); }//w w w .j a v a 2 s .com } }
From source file:it.av.fac.messaging.rabbitmq.RabbitMQChannelPool.java
public static synchronized Channel createChannel(Connection conn, String queueIn, String queueOut, String routingKeyIn, String routingKeyOut) throws IOException { String UID = obtainUniqueId(queueIn, queueOut, routingKeyIn, routingKeyOut); if (!POOL.containsKey(UID) || !POOL.get(UID).isOpen()) { Channel channel = conn.createChannel(); channel.exchangeDeclare(RabbitMQConstants.EXCHANGE, "direct", true); if (queueIn != null) { channel.queueDeclare(queueIn, false, false, true, null); channel.queueBind(queueIn, RabbitMQConstants.EXCHANGE, routingKeyIn); }/*from w w w .j ava 2s .c o m*/ if (queueOut != null) { channel.queueDeclare(queueOut, false, false, true, null); channel.queueBind(queueOut, RabbitMQConstants.EXCHANGE, routingKeyOut); } POOL.put(UID, channel); } return POOL.get(UID); }
From source file:itinno.example.ExampleSocialMediaStormDeclarator.java
/** * Main RabbitMQ declaration method. Will use RabbitMQ channel reference. * //from w ww . j a va 2s. c o m * Rabbit MQ Channel API: https://www.rabbitmq.com/releases/rabbitmq-java-client/v3.1.5/rabbitmq-java-client-javadoc-3.1.5/ (search for "Channel") * * @param channel rabbitmq channel */ @Override public void execute(Channel channel) { try { // Storm any possible arguments that could be passed Map<String, Object> args = new HashMap<>(); /* Declare the queue * * API: http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.html#queueDeclare(java.lang.String, boolean, boolean, boolean, boolean, java.util.Map)) * */ channel.queueDeclare(this.strQueueName, true, false, false, args); /* Declare the exchange * * API: http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.html#exchangeDeclare(java.lang.String, java.lang.String, boolean) */ channel.exchangeDeclare(this.strExchange, this.strExchangeType, true); /* * Bind the queue * * API: http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.html#queueBind(java.lang.String, java.lang.String, java.lang.String) */ channel.queueBind(this.strQueueName, this.strExchange, this.strRoutingKey); // Handle Exception and allow to continue } catch (Exception e) { System.err.println("Failed to execute RabbitMQ declarations. Details: " + e.getMessage()); e.printStackTrace(); } }
From source file:loanbroker.Aggregator.java
public void reciveFromNormalizer(Hashtable<String, Message> messageFroumBankList, Hashtable<String, Message> messagesFromNormalizer, ArrayList<Message> foundMessages) throws IOException, TimeoutException, Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName);//from www.j ava 2s .co m factory.setPort(5672); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // channel.exchangeDeclare(inputEXCHANGE_NAME, "direct"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.NormalizerToAggregator); System.out.println(" [*] Waiting for messages on " + ExchangeName.GLOBAL + RoutingKeys.NormalizerToAggregator + ". To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String m = new String(body, "UTF-8"); Gson gson = new GsonBuilder().create(); LoanResponse lp = gson.fromJson(m, LoanResponse.class); Message fm = new Message("" + lp.getSsn(), (int) lp.getInterestRate(), 0, lp.getBank()); messagesFromNormalizer.put(lp.getCorrelationId(), fm); System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + fm.toString() + "'"); try { checkLoanMessages(messageFroumBankList, messagesFromNormalizer, foundMessages); } catch (InterruptedException ex) { Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex); } catch (TimeoutException ex) { Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex); } } }; channel.basicConsume(queueName, true, consumer); }
From source file:loanbroker.Aggregator.java
public void reciveFromRecieptList(Hashtable<String, Message> messagesFromBankList) throws IOException, TimeoutException, Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName);/* ww w . j a v a2 s .c o m*/ factory.setPort(5672); factory.setUsername("student"); factory.setPassword("cph"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(ExchangeName.GLOBAL, "direct"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.RecipientListToAggregator); System.out.println(" [*] Waiting for messages on " + ExchangeName.GLOBAL + RoutingKeys.RecipientListToAggregator + ".. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String m = new String(body, "UTF-8"); // System.out.println("reciveFromRecieptList" + m); String p = properties.getCorrelationId(); if (p != null) { //send to translator Gson g = new Gson(); Message fm = g.fromJson(m, Message.class); if (fm.getBanks() != null) { Message k = new Message(fm.getSsn(), fm.getCreditScore(), fm.getLoanAmount(), fm.getLoanDuration()); k.setBanks(fm.getBanks()); messagesFromBankList.put(p, k); } System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + fm.toString() + "'"); // System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + m + "'"); } else { System.out.println("No correlationId"); } } }; channel.basicConsume(queueName, true, consumer); }
From source file:loanbroker.GetCreditScore.java
void recive() throws IOException, TimeoutException, InterruptedException, Exception { //setting the connection to the RabbitMQ server ConnectionFactory connfac = new ConnectionFactory(); connfac.setHost(hostName);/*from w ww. j a v a 2s . co m*/ connfac.setUsername("student"); connfac.setPassword("cph"); //make the connection Connection conn = connfac.newConnection(); //make the channel for messaging Channel chan = conn.createChannel(); //Declare a queue chan.exchangeDeclare(ExchangeName.OUTPUT_LOAN_REQUEST, "fanout"); String queueName = chan.queueDeclare().getQueue(); chan.queueBind(queueName, ExchangeName.OUTPUT_LOAN_REQUEST, ""); System.out.println( " [*] Waiting for messages on " + ExchangeName.OUTPUT_LOAN_REQUEST + ". To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(chan); chan.basicConsume(queueName, true, consumer); //start polling messages while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String m = new String(delivery.getBody()); System.out.println(" [x] Received '" + m + "'"); Gson gson = new GsonBuilder().create(); Message fm = gson.fromJson(m, Message.class); int creditScore = creditScore(fm.getSsn()); fm.setCreditScore(creditScore); fm.setSsn(fm.getSsn().replace("-", "")); send(fm); } }