List of usage examples for com.rabbitmq.client Channel basicConsume
String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
From source file:com.es.dashboard.ConnectionBrokerJPA.java
@PostConstruct public void init() { bigBaite = new LinkedList<>(); readings = new ArrayList<Reading>(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("systembus"); // RabbitMQ IP Connection connection = null; try {/*from w ww. ja va 2 s .co m*/ connection = factory.newConnection(); } catch (IOException ex) { logger.error(ex); } catch (TimeoutException ex) { logger.error(ex); } Channel channel = null; try { channel = connection.createChannel(); } catch (IOException ex) { logger.error(ex); } try { channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange } catch (IOException ex) { logger.error(ex); } AMQP.Queue.DeclareOk result = null; try { result = channel.queueDeclare("", false, true, false, null); } catch (IOException ex) { logger.error(ex); } String queuename = result.getQueue(); try { channel.queueBind(queuename, "sensors", "dashboard.response"); // Binding key is #, this will consume all messages } catch (IOException ex) { logger.error(ex); } logger.info(" [*] Waiting for messages. 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 message = new String(body, "UTF-8"); EventBus eventBus = EventBusFactory.getDefault().eventBus(); Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> myMap = gson.fromJson(message, type); if (envelope.getRoutingKey().equals("realtime.alarms")) { eventBus.publish("/jpa", message); return; } System.out.println(envelope.getRoutingKey()); logger.info(envelope.getRoutingKey()); //readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("value"), myMap.get("name"), myMap.get("room"))); //System.out.println("publishing " + msg_to_publish); eventBus.publish("/jpa", message); //System.out.println("published"); } }; try { //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}" // + "var timeoutdummy = window.setInterval(rpt,2000);"); channel.basicConsume(queuename, true, consumer); } catch (IOException ex) { ex.printStackTrace(); logger.error(ex); } }
From source file:com.espertech.esperio.amqp.AMQPSupportReceiveRunnable.java
License:Open Source License
public void run() { try {//ww w.j a v a 2s . c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments channel.queueDeclare(queueName, false, false, true, null); log.info("Start receiving messages"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); int count = 0; while (true) { final QueueingConsumer.Delivery msg = consumer.nextDelivery(waitMSecNextMsg); if (msg == null) { continue; } final byte[] bytes = msg.getBody(); callback.handleMessage(bytes); if (isShutdown()) { break; } } log.info("Completed publishing messages: " + count + " messages"); } catch (Exception ex) { log.error("Error attaching to AMQP: " + ex.getMessage(), ex); } }
From source file:com.espertech.esperio.amqp.AMQPSupportUtil.java
License:Open Source License
public static int drainQueue(String hostName, String queueName) { Connection connection = null; Channel channel = null; try {//from ww w . ja v a 2s. c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); connection = factory.newConnection(); channel = connection.createChannel(); // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments channel.queueDeclare(queueName, false, false, true, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); int count = 0; while (true) { final QueueingConsumer.Delivery msg = consumer.nextDelivery(1); if (msg == null) { return count; } } } catch (Exception ex) { log.error("Error attaching to AMQP: " + ex.getMessage(), ex); } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (IOException e) { e.printStackTrace(); } } } return -1; }
From source file:com.eventbook.controller.SpringbootPocController.java
@RequestMapping(value = "/rabbitMQReceiveTest", method = RequestMethod.GET) public String rabbitMQReceiveTest() { try {/*w w w . j ava2 s . c om*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("rabbitmq"); factory.setPort(5672); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. 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 message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); } catch (IOException | TimeoutException ex) { Logger.getLogger(SpringbootPocController.class.getName()).log(Level.SEVERE, null, ex); } return "Getting messages from RabbitMQ!!"; }
From source file:com.frannciscocabral.ufs.rabbitmq.Receiver.java
public static void main(String[] argv) throws java.io.IOException, java.lang.InterruptedException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override// w ww . j av a2 s. c o m public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
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(); }//w ww. j a v a2 s . c o 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.dann.wspusher.pubsub.subscriber.impl.RabbitMQSubscriberImpl.java
License:Apache License
@Override public void subscribe(String exchange, DataPusherWebSocket webSocket) { Connection connection = null; Channel channel = null; try {/*from w w w. jav a2s .co m*/ // FIXME Cache connection! ConnectionFactory factory = new ConnectionFactory(); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(exchange, DEFAULT_EXCHANGE_TYPE); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, exchange, ""); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); doWork(consumer, webSocket); } catch (Exception e) { logger.error("Error occured", e); throw new WsRuntimeException(e); } finally { RabbitMQResourceUtils.closeQuietly(channel); RabbitMQResourceUtils.closeQuietly(connection); } }
From source file:com.github.hexsmith.rabbitmq.consumer.MessageConsumer.java
License:Open Source License
public boolean consume(String queueName) { //RabbitMQ/*from w w w.j a va 2 s .com*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); Connection connection = null; Channel channel = null; try { connection = factory.newConnection(); channel = connection.createChannel(); //queue??queue //?queueDeclare???queue channel.queueDeclare(queueName, false, false, false, null); //?DefaultConsumerhandleDelivery???getByte()???String Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); logger.info("Received '" + message + "'"); } }; //?? channel.basicConsume(queueName, true, consumer); //???rabbitMQ } catch (IOException | TimeoutException e) { //?false logger.error("send message failed!", e); return false; } return true; }
From source file:com.github.hexsmith.rabbitmq.consumer.MultiMessageConsumer.java
License:Open Source License
public boolean consume(String queueName, String consumerName) { //RabbitMQ/*from ww w. j a va 2 s. c o m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.1"); Connection connection = null; Channel channel = null; try { connection = factory.newConnection(); channel = connection.createChannel(); //queue??queue //?queueDeclare???queue channel.queueDeclare(queueName, false, false, false, null); //?DefaultConsumerhandleDelivery???getByte()???String Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); logger.info("[{}]" + "Received '" + message + "'", consumerName); } }; //?? channel.basicConsume(queueName, true, consumer); //???rabbitMQ } catch (IOException | TimeoutException e) { //?false logger.error("send message failed!", e); return false; } return true; }
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 {/*from w ww . j a v a 2 s . c o m*/ 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) { } } } }