List of usage examples for com.rabbitmq.client Channel basicConsume
String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
From source file:OnlyPackege.TheMightyBank.java
public static void main(String[] args) throws Exception { JSONParser jsonParster = new JSONParser(); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel recvChannel = connection.createChannel(); recvChannel.exchangeDeclare(EXCHANGE_NAME, "fanout"); String queueName = recvChannel.queueDeclare().getQueue(); recvChannel.queueBind(queueName, EXCHANGE_NAME, ""); QueueingConsumer consumer = new QueueingConsumer(recvChannel); recvChannel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String responseQueue = delivery.getProperties().getReplyTo(); Channel sendChannel = connection.createChannel(); sendChannel.queueDeclare(responseQueue, false, false, false, null); String message = new String(delivery.getBody()); JSONObject recvObj = (JSONObject) jsonParster.parse(message); //to be deleted after testing System.out.println(" [x] Received '" + message + "'"); JSONObject obj = new JSONObject(); obj.put("ssn", recvObj.get("ssn")); obj.put("interestRate", Math.random() * 10); sendChannel.basicPublish("", responseQueue, null, obj.toJSONString().getBytes()); }/*from w w w . ja v a 2s . co m*/ }
From source file:org.apache.airavata.datacat.agent.messageBroker.AiravataUpdateListener.java
License:Apache License
public void startBroker() { (new Thread(new Runnable() { @Override/*from ww w . j ava 2s . c o m*/ public void run() { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RABBITMQ_HOST); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); channel.basicQos(1); channel.queueBind(queueName, EXCHANGE_NAME, BINDING_KEY); logger.debug("Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (runFileUpdateListener) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Message message = new Message(); ThriftUtils.createThriftFromBytes(delivery.getBody(), message); TBase event = null; if (message.getMessageType().equals(MessageType.EXPERIMENT_OUTPUT)) { ExperimentOutputCreatedEvent experimentOutputCreatedEvent = new ExperimentOutputCreatedEvent(); ThriftUtils.createThriftFromBytes(message.getEvent(), experimentOutputCreatedEvent); logger.debug(" Message Received with message id '" + message.getMessageId() + "' and with message type '" + message.getMessageType() + "' with experiment name " + experimentOutputCreatedEvent.getExperimentName()); event = experimentOutputCreatedEvent; logger.debug(" [x] Received FileInfo Message'"); process(experimentOutputCreatedEvent, message.getUpdatedTime()); logger.debug(" [x] Done Processing FileInfo Message"); } else { logger.debug("Recieved message of type ..." + message.getMessageType()); } } } catch (Exception e) { logger.error(e); } } })).start(); }
From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.AMQPMonitor.java
License:Apache License
@Override public boolean registerListener(MonitorID monitorID) throws AiravataMonitorException { // we subscribe to read user-host based subscription HostDescription host = monitorID.getHost(); String hostAddress = host.getType().getHostAddress(); // in amqp case there are no multiple jobs per each host, because once a job is put in to the queue it // will be picked by the Monitor, so jobs will not stay in this queueu but jobs will stay in finishQueue String channelID = CommonUtils.getChannelID(monitorID); if (availableChannels.get(channelID) == null) { try {/*from ww w . j av a2 s .c om*/ //todo need to fix this rather getting it from a file Connection connection = AMQPConnectionUtil.connect(amqpHosts, connectionName, proxyPath); Channel channel = null; channel = connection.createChannel(); availableChannels.put(channelID, channel); String queueName = channel.queueDeclare().getQueue(); BasicConsumer consumer = new BasicConsumer(new JSONMessageParser(), localPublisher); // here we use local publisher channel.basicConsume(queueName, true, consumer); String filterString = CommonUtils.getRoutingKey(monitorID.getUserName(), hostAddress); // here we queuebind to a particular user in a particular machine channel.queueBind(queueName, "glue2.computing_activity", filterString); logger.info("Using filtering string to monitor: " + filterString); } catch (IOException e) { logger.error("Error creating the connection to finishQueue the job:" + monitorID.getUserName()); } } return true; }
From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPBroadcastReceiverImpl.java
License:Apache License
public void Subscribe() throws AMQPException { if (callback != null) { try {/*from w ww . j a v a 2s . co m*/ Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_FANOUT, AMQPUtil.EXCHANGE_TYPE_FANOUT); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_FANOUT, ""); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); callback.onMessage(message); } } catch (Exception e) { throw new AMQPException(e); } } }
From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPReceiverImpl.java
License:Apache License
public void Subscribe(AMQPRoutingKey key) throws AMQPException { if (callback != null) { try {/* w w w . j a va2 s .c o m*/ Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_DIRECT, AMQPUtil.EXCHANGE_TYPE_DIRECT); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_DIRECT, key.getNativeKey()); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); callback.onMessage(message); } } catch (Exception e) { throw new AMQPException(e); } } }
From source file:org.apache.airavata.wsmg.client.amqp.rabbitmq.AMQPTopicReceiverImpl.java
License:Apache License
public void Subscribe(AMQPRoutingKey topic) throws AMQPException { if (callback != null) { try {/* w ww .j a va 2s . c om*/ Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(AMQPUtil.EXCHANGE_NAME_TOPIC, AMQPUtil.EXCHANGE_TYPE_TOPIC); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, AMQPUtil.EXCHANGE_NAME_TOPIC, topic.getNativeKey()); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); callback.onMessage(message); } } catch (Exception e) { throw new AMQPException(e); } } }
From source file:org.apache.axis2.transport.rabbitmq.RabbitMQSender.java
License:Open Source License
private void processResponse(RabbitMQConnectionFactory factory, MessageContext msgContext, String correlationID, String replyTo, Hashtable<String, String> eprProperties) throws IOException { Connection connection = factory.createConnection(); if (!RabbitMQUtils.isQueueAvailable(connection, replyTo)) { log.info("Reply-to queue : " + replyTo + " not available, hence creating a new one"); RabbitMQUtils.declareQueue(connection, replyTo, eprProperties); }//from www .j av a 2 s . c o m Channel channel = connection.createChannel(); QueueingConsumer consumer = new QueueingConsumer(channel); QueueingConsumer.Delivery delivery = null; RabbitMQMessage message = new RabbitMQMessage(); boolean responseFound = false; int timeout = RabbitMQConstants.DEFAULT_REPLY_TO_TIMEOUT; String timeoutStr = eprProperties.get(RabbitMQConstants.REPLY_TO_TIMEOUT); if (!StringUtils.isEmpty(timeoutStr)) { try { timeout = Integer.parseInt(timeoutStr); } catch (NumberFormatException e) { log.warn( "Number format error in reading replyto timeout value. Proceeding with default value (30000ms)", e); } } //start consuming without acknowledging String consumerTag = channel.basicConsume(replyTo, false, consumer); try { while (!responseFound) { log.debug("Waiting for next delivery from reply to queue " + replyTo); delivery = consumer.nextDelivery(timeout); if (delivery != null) { if (delivery.getProperties().getCorrelationId().equals(correlationID)) { responseFound = true; log.debug( "Found matching response with correlation ID : " + correlationID + ". Sending ack"); //acknowledge correct message channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } else { //not acknowledge wrong messages and re-queue log.debug("Found messages with wrong correlation ID. Re-queueing and sending nack"); channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true); } } } } catch (ShutdownSignalException e) { log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage()); } catch (InterruptedException e) { log.error("Error receiving message from RabbitMQ broker " + e.getLocalizedMessage()); } catch (ConsumerCancelledException e) { log.error("Error receiving message from RabbitMQ broker" + e.getLocalizedMessage()); } finally { if (channel != null || channel.isOpen()) { //stop consuming channel.basicCancel(consumerTag); } } if (delivery != null) { log.debug("Processing response from reply-to queue"); AMQP.BasicProperties properties = delivery.getProperties(); Map<String, Object> headers = properties.getHeaders(); message.setBody(delivery.getBody()); message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag()); message.setReplyTo(properties.getReplyTo()); message.setMessageId(properties.getMessageId()); //get content type from message String contentType = properties.getContentType(); if (contentType == null) { //if not get content type from transport parameter contentType = eprProperties.get(RabbitMQConstants.REPLY_TO_CONTENT_TYPE); if (contentType == null) { //if none is given, set to default content type log.warn("Setting default content type " + RabbitMQConstants.DEFAULT_CONTENT_TYPE); contentType = RabbitMQConstants.DEFAULT_CONTENT_TYPE; } } message.setContentType(contentType); message.setContentEncoding(properties.getContentEncoding()); message.setCorrelationId(properties.getCorrelationId()); if (headers != null) { message.setHeaders(headers); if (headers.get(RabbitMQConstants.SOAP_ACTION) != null) { message.setSoapAction(headers.get(RabbitMQConstants.SOAP_ACTION).toString()); } } MessageContext responseMsgCtx = createResponseMessageContext(msgContext); RabbitMQUtils.setSOAPEnvelope(message, responseMsgCtx, contentType); handleIncomingMessage(responseMsgCtx, RabbitMQUtils.getTransportHeaders(message), message.getSoapAction(), message.getContentType()); } }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testWriteQueue() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream() .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList()); p.apply(Create.of(data))/*from w ww . j av a2 s . c o m*/ .apply(RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.queueDeclare("TEST", true, false, false, null); Consumer consumer = new TestConsumer(channel, received); channel.basicConsume("TEST", true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java
License:Apache License
@Test public void testWriteExchange() throws Exception { final int maxNumRecords = 1000; List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream() .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList()); p.apply(Create.of(data)).apply(//from w w w .j a va2s . c o m RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withExchange("WRITE", "fanout")); final List<String> received = new ArrayList<>(); ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setUri("amqp://guest:guest@localhost:" + port); Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare("WRITE", "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, "WRITE", ""); Consumer consumer = new TestConsumer(channel, received); channel.basicConsume(queueName, true, consumer); p.run(); while (received.size() < maxNumRecords) { Thread.sleep(500); } assertEquals(maxNumRecords, received.size()); for (int i = 0; i < maxNumRecords; i++) { assertTrue(received.contains("Test " + i)); } } finally { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } }
From source file:org.apache.camel.component.rabbitmq.RabbitMQProducerIntTest.java
License:Apache License
@Test public void producedMessageIsReceived() throws InterruptedException, IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setPort(5672);/*from ww w . j ava 2 s .com*/ factory.setUsername("cameltest"); factory.setPassword("cameltest"); factory.setVirtualHost("/"); Connection conn = factory.newConnection(); final List<Envelope> received = new ArrayList<Envelope>(); Channel channel = conn.createChannel(); channel.queueDeclare("sammyq", false, false, true, null); channel.queueBind("sammyq", EXCHANGE, "route1"); channel.basicConsume("sammyq", true, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { received.add(envelope); } }); template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1"); Thread.sleep(500); assertEquals(1, received.size()); }