List of usage examples for com.rabbitmq.client Channel basicConsume
String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
From source file:org.mule.transport.amqp.AmqpConnector.java
License:Open Source License
public AmqpMessage consume(final Channel channel, final String queue, final boolean autoAck, final long timeout) throws IOException, InterruptedException { final QueueingConsumer consumer = new QueueingConsumer(channel); final String consumerTag = channel.basicConsume(queue, autoAck, consumer); final Delivery delivery = consumer.nextDelivery(timeout); channel.basicCancel(consumerTag);// w ww . j av a 2 s. com if (delivery == null) return null; return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(), delivery.getBody()); }
From source file:org.mule.transport.amqp.internal.client.MessageConsumer.java
License:Open Source License
public AmqpMessage consumeMessage(final Channel channel, final String queue, final boolean autoAck, final long timeout) throws IOException, InterruptedException { final long startTime = System.currentTimeMillis(); // try first with a basic get to potentially quickly retrieve a pending message final GetResponse getResponse = channel.basicGet(queue, autoAck); // if timeout is zero or if a message has been fetched don't go any further if ((timeout == 0) || (getResponse != null)) { return getResponse == null ? null : new AmqpMessage(null, getResponse.getEnvelope(), getResponse.getProps(), getResponse.getBody()); }//from w w w. j a va2 s . co m // account for the time taken to perform the basic get final long elapsedTime = System.currentTimeMillis() - startTime; final long actualTimeOut = timeout - elapsedTime; if (actualTimeOut < 0) { return null; } final QueueingConsumer consumer = new SingleMessageQueueingConsumer(channel); // false -> no AMQP-level autoAck with the SingleMessageQueueingConsumer final String consumerTag = channel.basicConsume(queue, false, consumer); try { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(actualTimeOut); if (delivery == null) { return null; } else { if (autoAck) { // ack only if auto-ack was requested, otherwise it's up to the caller to ack channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(), delivery.getBody()); } } finally { try { channel.basicCancel(consumerTag); } catch (IOException e) { /** * The broker could decide to cancel a subscription on certain situations */ if (LOGGER.isDebugEnabled()) { LOGGER.debug("Subscription to channel with consumerTag " + StringUtils.defaultString(consumerTag) + " could not be closed.", e); } } } }
From source file:org.ninjav.rabbitmq.TestReceive.java
@Test public void canReceiveMessageFromQueue() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); Consumer consumer;/* ww w . ja va 2s .com*/ consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { String message = new String(body, "UTF-8"); System.out.println("Message Received: " + message); } finally { channel.basicAck(envelope.getDeliveryTag(), false); } } }; boolean autoAck = false; channel.basicConsume(QUEUE_NAME, autoAck, consumer); try { Thread.sleep(100000); } catch (InterruptedException ex) { Logger.getLogger(TestReceive.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.objectweb.joram.mom.dest.amqp.AmqpAcquisition.java
License:Open Source License
/** * Create a new AMQP consumer for each connection available. *//* w ww .j av a 2s . c o m*/ public void updateConnections(List<LiveServerConnection> connections) { for (LiveServerConnection connection : connections) { if (!channels.containsKey(connection.getName())) { if (connectionNames == null || connectionNames.contains(connection.getName())) { if (logger.isLoggable(BasicLevel.DEBUG)) { logger.log(BasicLevel.DEBUG, "Creating a new consumer on queue " + amqpQueue + " for connection " + connection.getName()); } try { Channel channel = connection.getConnection().createChannel(); if (amqpQueuePassive) { channel.queueDeclarePassive(amqpQueue); } else { channel.queueDeclare(amqpQueue, amqpQueueDurable, amqpQueueExclusive, amqpQueueAutoDelete, null); } AmqpConsumer consumer = new AmqpConsumer(channel, connection.getName()); channel.basicConsume(amqpQueue, false, consumer); channels.put(connection.getName(), channel); } catch (Exception e) { logger.log(BasicLevel.ERROR, "Error while starting consumer on connection: " + connection.getName(), e); } } } } }
From source file:org.objectweb.proactive.extensions.amqp.remoteobject.AbstractAMQPRemoteObjectServer.java
License:Open Source License
public final void connect(boolean passive) throws IOException, ProActiveException { String queueName = AMQPUtils.computeQueueNameFromURI(rro.getURI()); final ReusableChannel reusableChannel = getReusableChannel(); boolean queueDeclared = false; try {/* w ww . ja v a 2 s .c o m*/ Channel channel = reusableChannel.getChannel(); createObjectQueue(channel, queueName); queueDeclared = true; if (logger.isDebugEnabled()) { logger.debug(String.format("declared queue %s", queueName)); } boolean autoAck = true; channel.basicConsume(queueName, autoAck, new Consumer(reusableChannel)); } catch (IOException e) { if (queueDeclared) { try { reusableChannel.getChannel().queueDelete(queueName); } catch (Exception queueDeleteException) { logger.warn("Failed to delete queue", queueDeleteException); } } reusableChannel.close(); throw e; } }
From source file:org.objectweb.proactive.extensions.amqp.remoteobject.AbstractFindQueuesRPCClient.java
License:Open Source License
public final List<URI> discover(URI uri, String exchangeName, long timeout) throws Exception { ReusableChannel reusableChannel = getReusableChannel(uri); try {/* www.j a v a 2s . c o m*/ Channel channel = reusableChannel.getChannel(); String replyQueueName = createReplyQueue(channel); QueueingConsumer consumer = new QueueingConsumer(channel); String consumerTag = channel.basicConsume(replyQueueName, true, consumer); List<URI> response = new ArrayList<URI>(); BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName) .type(DISCOVERY_QUEUES_MESSAGE_TYPE).build(); channel.basicPublish(exchangeName, "", props, null); TimeoutAccounter time = TimeoutAccounter.getAccounter(timeout); while (!time.isTimeoutElapsed()) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(200); if (delivery != null) { URI u = URI.create(new String(delivery.getBody())); response.add(u); } } // stop consuming, this also should delete temporary queue channel.basicCancel(consumerTag); reusableChannel.returnChannel(); return response; } catch (Exception e) { reusableChannel.close(); throw e; } }
From source file:org.openbaton.plugin.utils.PluginCaller.java
License:Apache License
public Serializable executeRPC(String methodName, Collection<Serializable> args, Type returnType) throws IOException, InterruptedException, PluginException { Channel channel = connection.createChannel(); String replyQueueName = channel.queueDeclare().getQueue(); String exchange = "plugin-exchange"; channel.queueBind(replyQueueName, exchange, replyQueueName); QueueingConsumer consumer = new QueueingConsumer(channel); String consumerTag = channel.basicConsume(replyQueueName, true, consumer); //Check if plugin is still up if (!RabbitManager.getQueues(brokerIp, username, password, managementPort).contains(pluginId)) throw new PluginException("Plugin with id: " + pluginId + " not existing anymore..."); String response;//from ww w. j av a 2 s.c om String corrId = UUID.randomUUID().toString(); PluginMessage pluginMessage = new PluginMessage(); pluginMessage.setMethodName(methodName); pluginMessage.setParameters(args); String message = gson.toJson(pluginMessage); BasicProperties props = new Builder().correlationId(corrId).replyTo(replyQueueName).build(); channel.basicPublish(exchange, pluginId, props, message.getBytes()); if (returnType != null) { while (true) { Delivery delivery = consumer.nextDelivery(); if (delivery.getProperties().getCorrelationId().equals(corrId)) { response = new String(delivery.getBody()); log.trace("received: " + response); break; } else { log.error("Received Message with wrong correlation id"); throw new PluginException( "Received Message with wrong correlation id. This should not happen, if it does please call us."); } } channel.queueDelete(replyQueueName); try { channel.close(); } catch (TimeoutException e) { e.printStackTrace(); } JsonObject jsonObject = gson.fromJson(response, JsonObject.class); JsonElement exceptionJson = jsonObject.get("exception"); if (exceptionJson == null) { JsonElement answerJson = jsonObject.get("answer"); Serializable ret = null; if (answerJson.isJsonPrimitive()) { ret = gson.fromJson(answerJson.getAsJsonPrimitive(), returnType); } else if (answerJson.isJsonArray()) { ret = gson.fromJson(answerJson.getAsJsonArray(), returnType); } else ret = gson.fromJson(answerJson.getAsJsonObject(), returnType); log.trace("answer is: " + ret); return ret; } else { PluginException pluginException; try { pluginException = new PluginException( gson.fromJson(exceptionJson.getAsJsonObject(), VimDriverException.class)); log.debug("Got Vim Driver Exception with server: " + ((VimDriverException) pluginException.getCause()).getServer()); } catch (Exception ignored) { pluginException = new PluginException( gson.fromJson(exceptionJson.getAsJsonObject(), Throwable.class)); } throw pluginException; } } else return null; }
From source file:org.opendaylight.federationmessagequeue.impl.RabbitMessageBus.java
License:Open Source License
@SuppressWarnings(value = { "checkstyle:illegalcatch" }) @Override// w ww . j a va2s . com public String attachHandler(String queueName, IGeneralFederationConsumer consumer) { MessageBusConnectionData messageBusConnectionData = queueNameToConnectionData.get(queueName); if (messageBusConnectionData != null) { Channel channel = messageBusConnectionData.channel; Consumer mqConsumer = createRabbitConsumer(consumer, channel); try { // start consuming from queue return channel.basicConsume(queueName, true, mqConsumer); } catch (IOException e) { String brokerIp = messageBusConnectionData.brokerIp; LOG.warn("Failed to consume from queue {} on broker {}", queueName, brokerIp, e); } } else { LOG.warn("AttachHandler failed - queue {} not found in the active connection map}", queueName); } return null; }
From source file:org.sdw.scheduler.QueueProcessor.java
License:Apache License
/** * Implementation of the Runnable interface's run method * Polls for messages in the shared queue and logs the results on arrival of message *//*from w ww. j a va2s. c om*/ @Override public void run() { try { ConnectionFactory factory = new ConnectionFactory(); factory.setUri(System.getenv("CLOUDAMQP_URL")); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String queueName = "work-queue-1"; Map<String, Object> params = new HashMap<>(); params.put("x-ha-policy", "all"); channel.queueDeclare(queueName, true, false, false, params); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); if (delivery != null) { String msg = new String(delivery.getBody(), "UTF-8"); LOG.info("Message Received: " + msg); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | URISyntaxException | ShutdownSignalException | ConsumerCancelledException | InterruptedException ex) { LOG.error(ex.getMessage(), ex); } }
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorController.java
License:Apache License
private void prepareQueue() throws ControllerException { if (this.notificationQueue != null) { this.actualQueueName = declareQueue(); bindQueue(this.actualQueueName); try {//w w w.j ava 2 s. c o m final Channel currentChannel = this.manager.channel(); final NotificationConsumer callback = new NotificationConsumer(currentChannel, this.notificationQueue); currentChannel.basicConsume(this.actualQueueName, false, callback); this.callbacks.add(callback); } catch (final IOException e) { throw new ControllerException(this.collector.getBrokerHost(), this.collector.getBrokerPort(), this.collector.getVirtualHost(), "Could not register consumer for queue '" + this.actualQueueName + "'", e); } } }