List of usage examples for com.rabbitmq.client Channel queueBind
Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;
From source file:com.abiquo.commons.amqp.impl.vsm.VSMConfiguration.java
License:Open Source License
@Override public void declareQueues(Channel channel) throws IOException { channel.queueDeclare(EVENT_SYNK_QUEUE, Durable, NonExclusive, NonAutodelete, null); channel.queueBind(EVENT_SYNK_QUEUE, VSM_EXCHANGE, VSM_ROUTING_KEY); }
From source file:com.cisco.oss.foundation.message.RabbitMQMessageConsumer.java
License:Apache License
RabbitMQMessageConsumer(String consumerName) { try {/*from www .j a v a 2 s . co m*/ this.consumerName = consumerName; Configuration subset = configuration.subset(consumerName); queueName = subset.getString("queue.name"); String filter = subset.getString("queue.filter", ""); boolean isAutoDelete = subset.getBoolean("queue.isAutoDelete", false); boolean isDurable = subset.getBoolean("queue.isDurable", true); boolean isSubscription = subset.getBoolean("queue.isSubscription", false); long expiration = subset.getLong("queue.expiration", 1800000); long maxLength = subset.getLong("queue.maxLength", -1); boolean deadLetterIsEnabled = subset.getBoolean("queue.deadLetterIsEnabled", true); String deadLetterExchangeName = subset.getString("queue.deadLetterExchangeName", DLQ); String subscribedTo = isSubscription ? subset.getString("queue.subscribedTo", "") : queueName; String exchangeType = subset.getString("queue.exchangeType", isSubscription ? "topic" : "direct"); boolean isExclusive = subset.getBoolean("queue.isExclusive", false); try { RabbitMQMessagingFactory.INIT_LATCH.await(); } catch (InterruptedException e) { LOGGER.error("error waiting for init to finish: " + e); } Channel channel = RabbitMQMessagingFactory.getChannel(); channel.exchangeDeclare(subscribedTo, exchangeType, isDurable, false, false, null); Map<String, Object> args = new HashMap<String, Object>(); if (maxLength > 0) { args.put("x-max-length", maxLength); } if (expiration > 0) { args.put("x-message-ttl", expiration); } if (deadLetterIsEnabled) { channel.exchangeDeclare(deadLetterExchangeName, exchangeType, isDurable, false, false, null); args.put("x-dead-letter-exchange", deadLetterExchangeName); } String queue = channel.queueDeclare(queueName, isDurable, isExclusive, isAutoDelete, args).getQueue(); Map<String, String> filters = ConfigUtil.parseSimpleArrayAsMap(consumerName + ".queue.filters"); if (filters != null && !filters.isEmpty()) { for (String routingKey : filters.values()) { channel.queueBind(queue, subscribedTo, routingKey); } } else { channel.queueBind(queue, subscribedTo, "#"); } consumer = new QueueingConsumer(channel); // channel.basicConsume(queueName, true, consumer); LOGGER.info("created rabbitmq consumer: {} on exchange: {}, queue-name: {}", consumerName, subscribedTo, queueName); } catch (IOException e) { throw new QueueException("Can't create consumer: " + e, e); } }
From source file:com.cisco.oss.foundation.message.RabbitMQMessageConsumerWithoutTL.java
License:Apache License
RabbitMQMessageConsumerWithoutTL(String consumerName) { try {//from w w w . j a va 2s .c om this.consumerName = consumerName; Configuration subset = configuration.subset(consumerName); queueName = subset.getString("queue.name"); String filter = subset.getString("queue.filter", ""); boolean isAutoDelete = subset.getBoolean("queue.isAutoDelete", false); boolean isDurable = subset.getBoolean("queue.isDurable", true); boolean isSubscription = subset.getBoolean("queue.isSubscription", false); long expiration = subset.getLong("queue.expiration", 1800000); long maxLength = subset.getLong("queue.maxLength", -1); boolean deadLetterIsEnabled = subset.getBoolean("queue.deadLetterIsEnabled", true); String deadLetterExchangeName = subset.getString("queue.deadLetterExchangeName", DLQ); String subscribedTo = isSubscription ? subset.getString("queue.subscribedTo", "") : queueName; String exchangeType = subset.getString("queue.exchangeType", isSubscription ? "topic" : "direct"); boolean isExclusive = subset.getBoolean("queue.isExclusive", false); try { RabbitMQMessagingFactory.INIT_LATCH.await(); } catch (InterruptedException e) { LOGGER.error("error waiting for init to finish: " + e); } Channel channel = RabbitMQMessagingFactory.createChannelWithoutTL(); channel.exchangeDeclare(subscribedTo, exchangeType, isDurable, false, false, null); Map<String, Object> args = new HashMap<String, Object>(); if (maxLength > 0) { args.put("x-max-length", maxLength); } if (expiration > 0) { args.put("x-message-ttl", expiration); } if (deadLetterIsEnabled) { channel.exchangeDeclare(deadLetterExchangeName, exchangeType, isDurable, false, false, null); args.put("x-dead-letter-exchange", deadLetterExchangeName); } String queue = channel.queueDeclare(queueName, isDurable, isExclusive, isAutoDelete, args).getQueue(); Map<String, String> filters = ConfigUtil.parseSimpleArrayAsMap(consumerName + ".queue.filters"); if (filters != null && !filters.isEmpty()) { for (String routingKey : filters.values()) { channel.queueBind(queue, subscribedTo, routingKey); } } else { channel.queueBind(queue, subscribedTo, "#"); } consumer = new QueueingConsumer(channel); // channel.basicConsume(queueName, true, consumer); LOGGER.info("created rabbitmq consumer: {} on exchange: {}, queue-name: {} channel number {}", consumerName, subscribedTo, queueName, channel.getChannelNumber()); } catch (IOException e) { throw new QueueException("Can't create consumer: " + e, e); } }
From source file:com.DeadLetterSender.java
License:Open Source License
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOSTNAME);//from w ww . java 2 s.c om Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); try { channel.exchangeDeclarePassive(EXCHANGE_NAME); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "direct", true); } try { channel.queueDeclarePassive(QUEUE_NAME); } catch (java.io.IOException e) { if (!channel.isOpen()) channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); } channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME); // Request Message String message = "<soapenv:Envelope" + " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + "<soapenv:Body>\n" + " <p:greet xmlns:p=\"http://service.wso2.org\">\n" + " <in>" + "IBM" + "</in>\n" + " </p:greet>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>"; // Adding Message Properties AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder(); builder.messageId("007"); builder.contentType("text/xml"); builder.correlationId("1111"); builder.replyTo(REPLY_QUEUE_NAME); builder.contentEncoding("UTF-8"); // Custom user properties Map<String, Object> headers = new HashMap<String, Object>(); headers.put("SOAP_ACTION", "getQuote"); builder.headers(headers); // Publish the message to exchange channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, builder.build(), message.getBytes()); channel.close(); connection.close(); }
From source file:com.ericsson.research.IoTFrameworkEndpoint.java
License:Open Source License
public void subscribe(String hostName, String StreamId, final DataPointCallback dataPointCallback) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); // listening on port 5672 Connection connection = factory.newConnection(); final Channel channel = connection.createChannel(); final String EXCHANGE_NAME = "streams." + StreamId; channel.exchangeDeclare(EXCHANGE_NAME, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, EXCHANGE_NAME, ""); dataPointCallback.setConnection(connection); boolean autoAck = true; channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) { @Override//from w w w.j ava2 s.c o m public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { DataPointNotification notification = gson.fromJson(new String(body), DataPointNotification.class); dataPointCallback.handleNotification(notification); } }); }
From source file:com.es.dashboard.ConnectionBroker.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 www.j ava 2 s . com 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", "realtime.sensordata"); // Binding key is #, this will consume all messages channel.queueBind(queuename, "sensors", "realtime.alarms"); // 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("/channel", message); return; } logger.info(envelope.getRoutingKey()); readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("data"), myMap.get("name"), myMap.get("room"))); eventBus.publish("/channel", message); } }; 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.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 {/* ww w . j a va 2s . 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.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(); }// www . j a v a2s .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.gettec.fsnip.fsn.web.controller.rest.deal.DealProblemRESTService.java
/** * ?/*from w w w .j a va2 s .c o m*/ * @param name * @param model * @return */ @RequestMapping(method = RequestMethod.POST, value = "/editDealToProblem/{id}") public View editDealToProblem(@PathVariable(value = "id") long id, Model model, HttpServletRequest req, HttpServletResponse resp) { try { AuthenticateInfo info = SSOClientUtil.validUser(req, resp); RabbitMQUtil rabbitMQUtil = new RabbitMQUtil(); Channel channel = rabbitMQUtil.connect(); channel.exchangeDeclare(SUPERVISE_JG, SUPERVISE_DIRECT, true); channel.queueDeclare(SUPERVISE_JG, true, false, false, null); channel.queueBind(SUPERVISE_JG, SUPERVISE_JG, SUPERVISE_KEY); JSONObject jsonObject = dealToProblemService.getDealProblemLogVO(id, info); channel.basicPublish("", SUPERVISE_JG, MessageProperties.PERSISTENT_TEXT_PLAIN, jsonObject.toString().getBytes("UTF-8")); model.addAttribute("status", true); } catch (Exception e) { model.addAttribute("status", false); e.printStackTrace(); } return JSON; }
From source file:com.gettec.fsnip.fsn.web.controller.rest.deal.DealProblemRESTService.java
@RequestMapping(method = RequestMethod.GET, value = "/notice/{id}/{status}/{pageStatus}") public View notice(@PathVariable("id") long id, @PathVariable("status") long status, @PathVariable("pageStatus") long pageStatus, Model model, HttpServletRequest request, HttpServletResponse response) {//from www .ja va 2 s.c o m try { DealProblem sendproblem = dealProblemService.noticeComplainById(id, status); if (status == 0) { //??RabbitMQ, RabbitMQUtil rabbitMQUtil = new RabbitMQUtil(); Channel channel = rabbitMQUtil.connect(); channel.exchangeDeclare(SUPERVISE_JG, SUPERVISE_DIRECT, true); channel.queueDeclare(SUPERVISE_JG, true, false, false, null); channel.queueBind(SUPERVISE_JG, SUPERVISE_JG, SUPERVISE_KEY); JSONObject jsonObject = dealToProblemService.getJsonDealToProblem(sendproblem, pageStatus); channel.basicPublish("", SUPERVISE_JG, MessageProperties.PERSISTENT_TEXT_PLAIN, jsonObject.toString().getBytes("UTF-8")); } else if (status == 1) { //? dealToProblemService.getNoticeDealToProblem(sendproblem); } } catch (Exception e) { e.printStackTrace(); } return JSON; }