List of usage examples for com.rabbitmq.client Channel queueBind
Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;
From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java
License:Apache License
/** Call to subscribe to interested set of events * * @param topic defines category and type of the events being subscribed to * @param subscriber subscriber that intends to receive event notification * @return UUID that represents the subscription with event bus * @throws EventBusException/*from w w w.j a v a 2 s.co m*/ */ @Override public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException { if (subscriber == null || topic == null) { throw new EventBusException("Invalid EventSubscriber/EventTopic object passed."); } // create a UUID, that will be used for managing subscriptions and also used as queue name // for on the queue used for the subscriber on the AMQP broker UUID queueId = UUID.randomUUID(); String queueName = queueId.toString(); try { String bindingKey = createBindingKey(topic); // store the subscriber details before creating channel _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber)); // create a channel dedicated for this subscription Connection connection = getConnection(); Channel channel = createChannel(connection); // create a queue and bind it to the exchange with binding key formed from event topic createExchange(channel, amqpExchangeName); channel.queueDeclare(queueName, false, false, false, null); channel.queueBind(queueName, amqpExchangeName, bindingKey); // register a callback handler to receive the events that a subscriber subscribed to channel.basicConsume(queueName, _autoAck, queueName, new DefaultConsumer(channel) { @Override public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName); if (queueDetails != null) { EventSubscriber subscriber = queueDetails.third(); String routingKey = envelope.getRoutingKey(); String eventSource = getEventSourceFromRoutingKey(routingKey); String eventCategory = getEventCategoryFromRoutingKey(routingKey); String eventType = getEventTypeFromRoutingKey(routingKey); String resourceType = getResourceTypeFromRoutingKey(routingKey); String resourceUUID = getResourceUUIDFromRoutingKey(routingKey); Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID); event.setDescription(new String(body)); // deliver the event to call back object provided by subscriber subscriber.onEvent(event); } } }); // update the channel details for the subscription Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName); queueDetails.second(channel); _subscribers.put(queueName, queueDetails); } catch (AlreadyClosedException closedException) { s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection"); } catch (ConnectException connectException) { s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName + " will be active after reconnection"); } catch (Exception e) { throw new EventBusException("Failed to subscribe to event due to " + e.getMessage()); } return queueId; }
From source file:org.apache.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java
License:Apache License
@Override public Firehose connect(final InputRowParser<ByteBuffer> firehoseParser, File temporaryDirectory) throws IOException { 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/* w w w . java 2 s .c o 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 row as a member variable should be safe since this will only be run * by a single thread. */ private InputRow nextRow; /** * 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; private Iterator<InputRow> nextIterator = Collections.emptyIterator(); @Override public boolean hasMore() { nextRow = null; try { if (nextIterator.hasNext()) { nextRow = nextIterator.next(); return true; } // Wait for the next delivery. This will block until something is available. final Delivery delivery = consumer.nextDelivery(); if (delivery != null) { lastDeliveryTag = delivery.getEnvelope().getDeliveryTag(); nextIterator = firehoseParser.parseBatch(ByteBuffer.wrap(delivery.getBody())).iterator(); if (nextIterator.hasNext()) { nextRow = nextIterator.next(); // 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; } @Nullable @Override public InputRow nextRow() { if (nextRow == null) { //Just making sure. log.wtf("I have nothing in delivery. Method hasMore() should have returned false."); return null; } return nextRow; } @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:org.apache.flume.amqp.AmqpConsumer.java
License:Apache License
/** * This method declares the exchange, queue and bindings needed by this consumer. * The method returns the queue name that will be used by this consumer. * * @param channel channel used to issue AMQP commands * @return queue that will have messages consumed from * @throws IOException thrown if there is any communication exception *//* ww w.ja v a 2 s . co m*/ @VisibleForTesting protected String declarationsForChannel(Channel channel) throws IOException { // setup exchange, queue and binding if (prefetchSize > 0) { channel.basicQos(prefetchSize); } // if exchange is provided if (exchangeName != null) { channel.exchangeDeclare(exchangeName, exchangeType, durableExchange); // named queue or server generated if (queueName == null) { queueName = channel.queueDeclare().getQueue(); } else { channel.queueDeclare(queueName, durableQueue, exclusiveQueue, autoDeleteQueue, null); } if (bindings.length > 0) { // multiple bindings for (String binding : bindings) { channel.queueBind(queueName, exchangeName, binding); } } else { // no binding given - this could be the case if it is a fanout exchange channel.queueBind(queueName, exchangeName, Constants.AMQP.SERVER_GENERATED_QUEUE_NAME); } } return queueName; }
From source file:org.apache.helix.recipes.rabbitmq.ConsumerThread.java
License:Apache License
@Override public void run() { Connection connection = null; try {//from ww w .j av a 2s . c om ConnectionFactory factory = new ConnectionFactory(); factory.setHost(_mqServer); connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); String bindingKey = _partition.toString(); channel.queueBind(queueName, EXCHANGE_NAME, bindingKey); System.out.println( " [*] " + _consumerId + " Waiting for messages on " + bindingKey + ". To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); String routingKey = delivery.getEnvelope().getRoutingKey(); System.out.println(" [x] " + _consumerId + " Received '" + routingKey + "':'" + message + "'"); } } catch (InterruptedException e) { System.err.println(" [-] " + _consumerId + " on " + _partition + " is interrupted ..."); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.java
License:Open Source License
/** * Create a Queue to store messages, this will used queueName parameter * * @throws IOException : if its enable to create the queue or exchange *//* ww w . java 2s .com*/ private void setQueue() throws IOException { Channel channel = null; try { channel = producerConnection.createChannel(); try { channel.queueDeclarePassive(queueName); } catch (java.io.IOException e) { logger.info("Queue :" + queueName + " not found.Declaring queue."); if (!channel.isOpen()) { channel = producerConnection.createChannel(); } //Hashmap with names and parameters can be used in the place of null argument //Eg: adding dead letter exchange to the queue //params: (queueName, durable, exclusive, autoDelete, paramMap) channel.queueDeclare(queueName, true, false, false, null); } //declaring exchange if (exchangeName != null) { try { channel.exchangeDeclarePassive(exchangeName); } catch (java.io.IOException e) { logger.info("Exchange :" + exchangeName + " not found. Declaring exchange."); if (!channel.isOpen()) { channel = producerConnection.createChannel(); } //params : ( exchangeName, exchangeType, durable, autoDelete, paramMap ) channel.exchangeDeclare(exchangeName, "direct", true, false, null); } channel.queueBind(queueName, exchangeName, routeKey); } } finally { channel.close(); } }
From source file:org.ballerinalang.messaging.rabbitmq.util.ChannelUtils.java
License:Open Source License
/** * Binds a queue to an exchange.//from w w w. j a v a 2 s .c o m * * @param channel RabbitMQ Channel object. * @param queueName Name of the queue. * @param exchangeName Name of the exchange. * @param bindingKey The binding key used for the binding. */ public static void queueBind(Channel channel, String queueName, String exchangeName, String bindingKey) { try { channel.queueBind(queueName, exchangeName, bindingKey); } catch (Exception e) { String errorMessage = "An error occurred while binding the queue to an exchange "; throw new RabbitMQConnectorException(errorMessage + e.getMessage(), e); } }
From source file:org.elasticsoftware.elasticactors.rabbitmq.cpt.RabbitMQMessagingService.java
License:Apache License
private void ensureQueueExists(final Channel channel, final String queueName) throws IOException { // ensure we have the queue created on the broker AMQP.Queue.DeclareOk result = channel.queueDeclare(queueName, true, false, false, null); // and bound to the exchange channel.queueBind(queueName, exchangeName, queueName); }
From source file:org.hp.samples.ProcessMessage.java
License:Open Source License
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(200);// w w w . j a v a2 s .c o m PrintWriter writer = response.getWriter(); writer.println("Here's your message:"); // Pull out the RABBITMQ_URL environment variable String uri = System.getenv("RABBITMQ_URL"); ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // Create the queue channel.queueDeclare("hello", false, false, false, null); String routingKey = "thekey"; String exchangeName = "exchange"; // Declare an exchange and bind it to the queue channel.exchangeDeclare(exchangeName, "direct", true); channel.queueBind("hello", exchangeName, routingKey); // Grab the message from the HTML form and publish it to the queue String message = request.getParameter("message"); channel.basicPublish(exchangeName, routingKey, null, message.getBytes()); writer.println(" Message sent to queue '" + message + "'"); boolean autoAck = false; // Get the response message GetResponse responseMsg = channel.basicGet("hello", autoAck); if (responseMsg == null) { // No message retrieved. } else { byte[] body = responseMsg.getBody(); // Since getBody() returns a byte array, convert to a string for // the user. String bodyString = new String(body); long deliveryTag = responseMsg.getEnvelope().getDeliveryTag(); writer.println("Message received: " + bodyString); // Acknowledge that we received the message so that the queue // removes the message so that it's not sent to us again. channel.basicAck(deliveryTag, false); } writer.close(); }
From source file:org.mule.transport.amqp.AmqpEndpointUtil.java
License:Open Source License
private static void bindQueue(final Channel channel, final ImmutableEndpoint endpoint, final String exchangeName, final String routingKey, final String queueName) throws IOException { if (StringUtils.isBlank(exchangeName)) { // default exchange name -> can not bind a queue to it throw new MuleRuntimeException(MessageFactory.createStaticMessage( "No queue can be programmatically bound to the default exchange: " + endpoint)); }/* w ww . jav a 2 s .c o m*/ // bind queue to exchange channel.queueBind(queueName, exchangeName, routingKey); LOG.info( "Bound queue: " + queueName + " to exchange: " + exchangeName + " with routing key: " + routingKey); }
From source file:org.mule.transport.amqp.internal.client.AmqpDeclarer.java
License:Open Source License
public void declareBinding(final Channel channel, final ImmutableEndpoint endpoint, final String exchangeName, final String routingKey, final String queueName) throws IOException { if (endpointUtil.isDefaultExchange(exchangeName)) { if (logger.isDebugEnabled()) { logger.debug("Skipped binding of queue: " + queueName + " to default exchange"); }// w ww. j a v a2 s . co m return; } // bind queue to exchange String[] routingKeyArray = routingKey.split(","); for (int i = 0; i < routingKeyArray.length; i++) { channel.queueBind(queueName, exchangeName, routingKeyArray[i].trim()); } logger.info( "Bound queue: " + queueName + " to exchange: " + exchangeName + " with routing key: " + routingKey); }