List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
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 w w.j av a 2 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.publisher.impl.RabbitMQPublisherImpl.java
License:Apache License
public void publish(String exchange, String message) { Connection connection = null; Channel channel = null;//from w ww. j a va 2 s . com try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(WsConfig.getMQServerHost()); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(exchange, EXCHANGE_TYPE); channel.basicPublish(exchange, "", null, message.getBytes(WsConstants.ENCODING_UTF8)); } catch (Exception e) { logger.error("Publishing message faile", e); throw new WsRuntimeException("Publishig message failed", e); } finally { RabbitMQResourceUtils.closeQuietly(channel); RabbitMQResourceUtils.closeQuietly(connection); } }
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;/* w w w. ja va 2 s. c om*/ try { // 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//w ww . ja v a 2s.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 + "'"); } }; //?? 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 w ww .ja v a2s . 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 + "'", 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.hexsmith.rabbitmq.producer.MessageProducer.java
License:Open Source License
public boolean sendMessage(String message) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.7"); Connection connection = null; Channel channel = null;/*from ww w . j av a 2 s .c o m*/ try { connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); logger.info("send message = {}", message); channel.close(); connection.close(); } catch (IOException | TimeoutException e) { logger.error("send message failed!,exception message is {}", e); return false; } return true; }
From source file:com.github.hexsmith.rabbitmq.producer.MessageProducer.java
License:Open Source License
public boolean sendMulitMessage(String message) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("127.0.0.7"); Connection connection = null; Channel channel = null;/*from ww w . jav a 2 s.c om*/ try { connection = factory.newConnection(); channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); int i = 0; int loop = 0; String originalMessage = message; while (loop < 10000) { loop++; message += i++; channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); logger.info("send message = {}", message); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } message = originalMessage; } channel.close(); connection.close(); } catch (IOException | TimeoutException e) { logger.error("send message failed!,exception message is {}", e); return false; } return true; }
From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java
License:Apache License
public AmqpActionQueue(ConnectionFactory factory, String queue, String exchange, String routingKey) throws IOException, TimeoutException { this.factory = factory; this.queue = queue; this.exchange = exchange; this.routingKey = routingKey; Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchange, "direct", true); channel.queueDeclare(queue, true, false, false, null); channel.queueBind(queue, exchange, routingKey); }
From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java
License:Apache License
@Override public void submitTask(AsyncExecutionRequest request) throws AsyncTaskSubmissionException { try {/*www. j a va 2 s. c o m*/ Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.basicPublish(this.exchange, this.routingKey, null, serialize(request)); } catch (IOException | TimeoutException ex) { LOGGER.error("Failed to submit action execution request", ex); throw new AsyncTaskSubmissionException(); } }
From source file:com.github.kislayverma.dredd.action.async.amqp.AmqpActionQueue.java
License:Apache License
@Override public AsyncExecutionRequest getTask() throws AsyncTaskConsumptionException { try {//from ww w .ja va 2 s . c o m 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 }