List of usage examples for com.rabbitmq.client Channel basicAck
void basicAck(long deliveryTag, boolean multiple) throws IOException;
From source file:ThreadWorkers.java
public void run() { System.out.println("MyThread running"); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = null; try {//w ww .ja v a2s . c o m connection = factory.newConnection(); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } Channel channel = null; try { channel = connection.createChannel(); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } try { channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); try { channel.basicQos(1); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } QueueingConsumer consumer = new QueueingConsumer(channel); try { channel.basicConsume(TASK_QUEUE_NAME, false, consumer); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } while (true) { QueueingConsumer.Delivery delivery = null; try { delivery = consumer.nextDelivery(); } catch (InterruptedException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } catch (ShutdownSignalException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } catch (ConsumerCancelledException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); try { doWork(message); } catch (InterruptedException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(" [x] Done"); try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:ReplyUtil.java
public void getReply() throws IOException, InterruptedException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_REPLY_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1);//from w ww . ja va2s . c o m QueueingConsumer consumer2 = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_REPLY_NAME, false, consumer2); while (true) { QueueingConsumer.Delivery delivery = consumer2.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Receiving reply from worker::'" + message + "'"); //doWork(message); //System.out.println(" [x] Done" ); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:com.abiquo.commons.amqp.util.ConsumerUtils.java
License:Open Source License
public static void ackMessage(Channel channel, long tag) throws IOException { channel.basicAck(tag, false); }
From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.PublishSubcribeRabbitMQWork.java
@Override public void run() { try {//from www. j a v a 2s . c om Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO, "Work Schedule Polling started @ ".concat(uuid)); if (ipsm == null) { try { Class<?> className = Class .forName(((RabbitMQActivationSpec) activationSpec).getDestinationType()); ipsm = (IPublishSubscribeMessage) className.getConstructor().newInstance(); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(BootStrapRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } final Channel channel; RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance(); if (instance.getConnectionRequestInfo(activationSpec) == null) { instance.setConnectionRequestInfo(activationSpec, new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(), ((RabbitMQActivationSpec) activationSpec).getPassword(), ((RabbitMQActivationSpec) activationSpec).getHost(), ((RabbitMQActivationSpec) activationSpec).getPort(), ((RabbitMQActivationSpec) activationSpec).getVirtualHost())); } try { connection = instance.getConnection(); channel = connection.createChannel(); channel.exchangeDeclare(((RabbitMQActivationSpec) activationSpec).getExchangeName(), ipsm.getSubscribeType(), isExchangeDurabe(ipsm)); final Consumer consumer = new DefaultConsumer(channel) { @Override public void handleConsumeOk(String consumerTag) { super.handleConsumeOk(consumerTag); } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); if (!envelope.isRedeliver()) { try { RabbitMQMessage mQMessage = new RabbitMQMessage(); mQMessage.getMessages().add(body); try { receiveMessages(mQMessage); } catch (ResourceException ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } finally { channel.basicAck(envelope.getDeliveryTag(), true); } } } }; channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer); } catch (IOException ex) { Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } catch (Exception ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } }
From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.QueueRabbitMQWork.java
@Override public void run() { try {/* w w w . ja va 2s.com*/ Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO, "Work Schedule Polling started @ ".concat(uuid)); final Channel channel; RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance(); if (instance.getConnectionRequestInfo(activationSpec) == null) { instance.setConnectionRequestInfo(activationSpec, new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(), ((RabbitMQActivationSpec) activationSpec).getPassword(), ((RabbitMQActivationSpec) activationSpec).getHost(), ((RabbitMQActivationSpec) activationSpec).getPort(), ((RabbitMQActivationSpec) activationSpec).getVirtualHost())); } try { connection = instance.getConnection(); channel = connection.createChannel(); channel.queueDeclarePassive(((RabbitMQActivationSpec) activationSpec).getQueueName()); channel.basicQos(0); final Consumer consumer = new DefaultConsumer(channel) { @Override public void handleConsumeOk(String consumerTag) { super.handleConsumeOk(consumerTag); } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); if (!envelope.isRedeliver()) { try { RabbitMQMessage mQMessage = new RabbitMQMessage(); mQMessage.getMessages().add(body); try { receiveMessages(mQMessage); } catch (ResourceException ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } finally { channel.basicAck(envelope.getDeliveryTag(), true); } } } }; channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer); } catch (IOException ex) { Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } } catch (Exception ex) { Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex); } }
From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMain.java
public static void main(String[] args) { //activate logging level if it is DEBUG, default is INFO so no need for any //action if it is otherwise Injector propInjector = Guice.createInjector(new GeminiPropertiesModule()); GeminiProperties properties = propInjector.getInstance(GeminiProperties.class); if (properties.getProperties().getProperty("LOGGING_LEVEL").equals("DEBUG")) { Configurator.defaultConfig().level(Level.DEBUG).activate(); }/*from w ww . ja v a2 s .co m*/ //inject the mapper as it will be used in all the threads Injector mapperInjector = Guice.createInjector(new GeminiMapperModule()); mapper = mapperInjector.getInstance(GeminiMapper.class); //the app.yml to deployment.yml converter Thread yamlConverterThread = new Thread(() -> { //setup the message receiver final Connection connection; final Channel channel; final QueueingConsumer consumer; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST")); String queueName = null; try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"), properties.getProperties().getProperty("YAML_MAPPER_TOPIC")); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (IOException | NullPointerException | NumberFormatException ex) { Logger.error("Fatal Error: YAML Mapper - could not connect to messaging system. Exception: {}", ex); return; } QueueingConsumer.Delivery delivery = null; while (true) { try { delivery = consumer.nextDelivery(); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) { Logger.error("Fatal Error: YAML Mapper - could not retrieve message. Exception: {}", ex); continue; } String routingKey = delivery.getEnvelope().getRoutingKey(); String jsonBody = new String(delivery.getBody()); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE Integer status = 0; if (routingKey.equals(properties.getProperties().getProperty("YAML_MAPPER_MAP_APP"))) { status = mapApptoDeployment(jsonBody); } else { continue; } if (status == 0) { try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.error("Could not ack message. Exception: {}", ex); } } else { //failed so requeue the message try { channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true); } catch (IOException ex) { Logger.error("Could not nack message. Exception: {}", ex); } } } }); yamlConverterThread.start(); //the networking message recevier Thread networkingThread = new Thread(() -> { //setup the message receiver final Connection connection; final Channel channel; final QueueingConsumer consumer; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST")); String queueName = null; try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"), properties.getProperties().getProperty("NETWORK_TOPIC")); // channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT"))); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (IOException | NullPointerException | NumberFormatException ex) { Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex); return; } QueueingConsumer.Delivery delivery = null; while (true) { try { delivery = consumer.nextDelivery(); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) { Logger.error("Could not get message from queue. Exception: {}", ex); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE continue; } String routingKey = delivery.getEnvelope().getRoutingKey(); String jsonBody = new String(delivery.getBody()); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_CREATE"))) { createNetwork(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_UPDATE"))) { updateNetwork(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_DELETE"))) { deleteNetwork(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_CREATE"))) { createSubnet(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_UPDATE"))) { updateSubnet(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_DELETE"))) { deleteSubnet(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_CREATE"))) { createRouter(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_UPDATE"))) { updateRouter(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_DELETE"))) { deleteRouter(jsonBody); } try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.error("Could not ack message. Exception: {}", ex); } } }); networkingThread.start(); //the load balancer Thread lbThread = new Thread(() -> { }); lbThread.start(); //the security thread Thread securityThread = new Thread(() -> { //setup the message receiver final Connection connection; final Channel channel; final QueueingConsumer consumer; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST")); String queueName = null; try { connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic"); queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"), properties.getProperties().getProperty("SECURITY_TOPIC")); // channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT"))); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (IOException | NullPointerException | NumberFormatException ex) { Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex); return; } QueueingConsumer.Delivery delivery = null; while (true) { try { delivery = consumer.nextDelivery(); } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) { Logger.error("Could not get message from queue. Exception: {}", ex); continue; } String routingKey = delivery.getEnvelope().getRoutingKey(); String jsonBody = new String(delivery.getBody()); //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_CREATE"))) { createSecurityGroup(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_UPDATE"))) { updateSecurityGroup(jsonBody); } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_DELETE"))) { deleteSecurityGroup(jsonBody); } else if (routingKey .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_CREATE"))) { createSecurityGroupRule(jsonBody); } else if (routingKey .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_UPDATE"))) { updateSecurityGroupRule(jsonBody); } else if (routingKey .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_DELETE"))) { deleteSecurityGroupRule(jsonBody); } try { channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } catch (IOException ex) { Logger.error("Could not ack message. Exception: {}", ex); } } }); securityThread.start(); }
From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java
License:Apache License
@Override public AsyncExecutionRequest getTask() throws AsyncTaskConsumptionException { try {// w ww . j a v a2 s .c om Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); GetResponse response = channel.basicGet(this.queue, false); if (response != null) { AsyncExecutionRequest message = deserialize(response.getBody()); long deliveryTag = response.getEnvelope().getDeliveryTag(); channel.basicAck(deliveryTag, true); return message; } } catch (IOException | TimeoutException | ClassNotFoundException ex) { LOGGER.error("Failed to read message from the queue", ex); throw new AsyncTaskConsumptionException(); } return null; // Won't ever reach here }
From source file:com.github.liyp.rabbitmq.rpc.RPCServer.java
License:Apache License
public static void main(String[] argv) { Connection connection = null; Channel channel = null; try {// w w w. j a v a2 s . c om ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(RPC_QUEUE_NAME, false, consumer); System.out.println(" [x] Awaiting RPC requests"); while (true) { String response = null; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()) .build(); try { String message = new String(delivery.getBody(), "UTF-8"); int n = Integer.parseInt(message); System.out.println(" [.] fib(" + message + ")"); response = "" + fib(n); } catch (Exception e) { System.out.println(" [.] " + e.toString()); response = ""; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8")); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception ignore) { } } } }
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
@Override public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override/*from w w w . j ava2 s . c o m*/ public Message doInRabbit(Channel channel) throws IOException { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); // Response can be null is the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; } }); }
From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java
License:Apache License
@SuppressWarnings("unchecked") private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback, final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException { return this.execute(new ChannelCallback<Boolean>() { @Override/* ww w. j a v a 2s . c o m*/ public Boolean doInRabbit(Channel channel) throws Exception { boolean channelTransacted = RabbitTemplate.this.isChannelTransacted(); GetResponse response = channel.basicGet(queueName, !channelTransacted); // Response can be null in the case that there is no message on // the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel); if (channelLocallyTransacted) { channel.basicAck(deliveryTag, false); } else if (channelTransacted) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(), channel, deliveryTag); } Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response); Object receive = receiveMessage; if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) { receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage); } S reply; try { reply = callback.handle((R) receive); } catch (ClassCastException e) { StackTraceElement[] trace = e.getStackTrace(); if (trace[0].getMethodName().equals("handle") && trace[1].getFileName().equals("RabbitTemplate.java")) { throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback + "' can't handle received object '" + receive + "'", e); } else { throw e; } } if (reply != null) { Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply); Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply); MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties(); MessageProperties replyMessageProperties = replyMessage.getMessageProperties(); Object correlation = RabbitTemplate.this.correlationKey == null ? receiveMessageProperties.getCorrelationId() : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey); if (RabbitTemplate.this.correlationKey == null || correlation == null) { // using standard correlationId property if (correlation == null) { String messageId = receiveMessageProperties.getMessageId(); if (messageId != null) { correlation = messageId.getBytes(RabbitTemplate.this.encoding); } } replyMessageProperties.setCorrelationId((byte[]) correlation); } else { replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation); } // 'doSend()' takes care about 'channel.txCommit()'. RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage, null); } else if (channelLocallyTransacted) { channel.txCommit(); } return true; } return false; } }); }