List of usage examples for com.rabbitmq.client DefaultConsumer DefaultConsumer
public DefaultConsumer(Channel channel)
From source file:org.mule.transport.rmq.RmqMessageReceiver.java
License:Open Source License
public void doStart() { //Create a listening consumer. consumer = new DefaultConsumer(channel) { @Override//w ww . j a va 2s. c o m public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); MessageAdapter adapter; try { adapter = connector.getMessageAdapter(new Delivery(envelope, properties, body)); routeMessage(new DefaultMuleMessage(adapter), endpoint.isSynchronous()); } catch (MessagingException e) { logger.error(e.getMessage()); } catch (MuleException e) { logger.error(e.getMessage()); } this.getChannel().basicAck(deliveryTag, false); } }; try { channel.basicConsume(queue, noAck, consumerTag, noLocal, cExclusive, consumer); } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:org.ninjav.rabbitmq.TestReceive.java
@Test public void canReceiveMessageFromQueue() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); Consumer consumer;/*from www . ja v a2 s.c om*/ consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { String message = new String(body, "UTF-8"); System.out.println("Message Received: " + message); } finally { channel.basicAck(envelope.getDeliveryTag(), false); } } }; boolean autoAck = false; channel.basicConsume(QUEUE_NAME, autoAck, consumer); try { Thread.sleep(100000); } catch (InterruptedException ex) { Logger.getLogger(TestReceive.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.nodex.mods.amqp.Channel.java
License:Apache License
public void subscribe(final String queueName, final boolean autoAck, final AmqpMsgCallback messageCallback) { NodexImpl.instance.executeInBackground(new Runnable() { public void run() { try { channel.basicConsume(queueName, autoAck, "blah", new DefaultConsumer(channel) { @Override// ww w . ja v a 2s . c om public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { AmqpProps props = properties == null ? null : new AmqpProps(properties); messageCallback.onMessage(props, body); } }); } catch (IOException e) { //TODO handle exceptionHandler by passing them back on callback e.printStackTrace(); } } }); }
From source file:org.openbaton.plugin.PluginListener.java
License:Apache License
@Override public void run() { try {/* w w w .j a v a2 s . c om*/ initRabbitMQ(); } catch (IOException | TimeoutException e) { e.printStackTrace(); return; } try { Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { AMQP.BasicProperties props = new AMQP.BasicProperties.Builder() .correlationId(properties.getCorrelationId()).build(); executor.execute(() -> { String message; try { message = new String(body, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } log.trace("Received message"); log.trace("Message content received: " + message); PluginAnswer answer = new PluginAnswer(); try { answer.setAnswer(executeMethod(message)); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); answer.setException(e.getTargetException()); } catch (Exception e) { e.printStackTrace(); answer.setException(e); } String response; try { response = gson.toJson(answer); log.trace("Answer is: " + response); log.trace("Reply queue is: " + properties.getReplyTo()); channel.basicPublish(exchange, properties.getReplyTo(), props, response.getBytes()); } catch (Throwable e) { e.printStackTrace(); answer.setException(e); log.trace("Answer is: " + answer); log.trace("Reply queue is: " + properties.getReplyTo()); try { channel.basicPublish(exchange, properties.getReplyTo(), props, gson.toJson(answer).getBytes()); } catch (IOException ex) { log.error(String.format("Thread %s got an exception: %s", Thread.currentThread().getName(), e.getMessage())); e.printStackTrace(); } } }); channel.basicAck(envelope.getDeliveryTag(), false); log.trace(String.format("Ack %d", envelope.getDeliveryTag())); synchronized (this) { this.notify(); } } }; channel.basicConsume(pluginId, false, consumer); // Wait and be prepared to consume the message from RPC client. while (true) { synchronized (consumer) { try { consumer.wait(); } catch (InterruptedException e) { log.info("Ctrl-c received"); System.exit(0); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) try { connection.close(); } catch (IOException ignored) { } } try { if (channel == null || connection == null) System.exit(3); channel.close(); connection.close(); } catch (IOException | TimeoutException e) { e.printStackTrace(); } }
From source file:org.opendaylight.federationmessagequeue.impl.RabbitMessageBus.java
License:Open Source License
private Consumer createRabbitConsumer(IGeneralFederationConsumer consumer, Channel channel) { Consumer mqConsumer = new DefaultConsumer(channel) { /*/*from w w w . j a v a2 s .c o m*/ * The methods of this interface are invoked in a dispatch thread which is separate from the Connection's * thread. The Consumers on a particular Channel are invoked serially on one or more dispatch threads. */ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Kryo kryo = new Kryo(); kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); Input input = new Input(new ByteArrayInputStream(body)); try { Bundle bundle = FrameworkUtil.getBundle(RabbitMessageBus.class); BundleContext bundleContext = bundle.getBundleContext(); BundleDelegatingClassLoader loader = new BundleDelegatingClassLoader(bundleContext.getBundle(), Thread.currentThread().getContextClassLoader()); kryo.setClassLoader(loader); Object readObject = kryo.readClassAndObject(input); if (readObject instanceof AbstractFederationMessage) { RabbitCounters.received_msg.inc(); consumer.consumeMsg((AbstractFederationMessage) readObject); } else { LOG.error("Received an object not of type AbstractFederationMessage, type was: {}", readObject.getClass().getName()); } LOG.trace("Deserialized {}", readObject); } catch (Throwable e) { LOG.error("Failed in readObject: " + e.getMessage(), e); return; } } }; return mqConsumer; }
From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryIntegrationTests.java
License:Apache License
@Test public void testHardErrorAndReconnect() throws Exception { RabbitTemplate template = new RabbitTemplate(connectionFactory); RabbitAdmin admin = new RabbitAdmin(connectionFactory); Queue queue = new Queue("foo"); admin.declareQueue(queue);/*from w ww .j ava2 s . com*/ final String route = queue.getName(); final CountDownLatch latch = new CountDownLatch(1); try { template.execute(new ChannelCallback<Object>() { @Override public Object doInRabbit(Channel channel) throws Exception { channel.getConnection().addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { logger.info("Error", cause); latch.countDown(); // This will be thrown on the Connection thread just before it dies, so basically ignored throw new RuntimeException(cause); } }); String tag = channel.basicConsume(route, new DefaultConsumer(channel)); // Consume twice with the same tag is a hard error (connection will be reset) String result = channel.basicConsume(route, false, tag, new DefaultConsumer(channel)); fail("Expected IOException, got: " + result); return null; } }); fail("Expected AmqpIOException"); } catch (AmqpIOException e) { // expected } template.convertAndSend(route, "message"); assertTrue(latch.await(1000, TimeUnit.MILLISECONDS)); String result = (String) template.receiveAndConvert(route); assertEquals("message", result); result = (String) template.receiveAndConvert(route); assertEquals(null, result); }
From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java
License:Apache License
@Test public void testProperties() throws Exception { SingleConnectionFactory connectionFactory = new SingleConnectionFactory(); connectionFactory.setHost("localhost"); RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); String queueName = "test.properties." + System.currentTimeMillis(); try {/*from w w w . j a v a 2s. c o m*/ rabbitAdmin.declareQueue(new Queue(queueName)); new RabbitTemplate(connectionFactory).convertAndSend(queueName, "foo"); int n = 0; while (n++ < 100 && messageCount(rabbitAdmin, queueName) == 0) { Thread.sleep(100); } assertTrue("Message count = 0", n < 100); Channel channel = connectionFactory.createConnection().createChannel(false); DefaultConsumer consumer = new DefaultConsumer(channel); channel.basicConsume(queueName, true, consumer); n = 0; while (n++ < 100 && messageCount(rabbitAdmin, queueName) > 0) { Thread.sleep(100); } assertTrue("Message count > 0", n < 100); Properties props = rabbitAdmin.getQueueProperties(queueName); assertNotNull(props.get(RabbitAdmin.QUEUE_CONSUMER_COUNT)); assertEquals(1, props.get(RabbitAdmin.QUEUE_CONSUMER_COUNT)); channel.close(); } finally { rabbitAdmin.deleteQueue(queueName); connectionFactory.destroy(); } }
From source file:org.springframework.amqp.rabbit.core.RabbitManagementTemplateTests.java
License:Apache License
@Test public void testSpecificQueue() throws Exception { RabbitAdmin admin = new RabbitAdmin(connectionFactory); Map<String, Object> args = Collections.<String, Object>singletonMap("foo", "bar"); Queue queue1 = QueueBuilder.nonDurable(UUID.randomUUID().toString()).autoDelete().withArguments(args) .build();/* ww w .j a v a 2 s .c o m*/ admin.declareQueue(queue1); Queue queue2 = QueueBuilder.durable(UUID.randomUUID().toString()).withArguments(args).build(); admin.declareQueue(queue2); Channel channel = this.connectionFactory.createConnection().createChannel(false); String consumer = channel.basicConsume(queue1.getName(), false, "", false, true, null, new DefaultConsumer(channel)); QueueInfo qi = this.template.getClient().getQueue("/", queue1.getName()); int n = 0; while (n++ < 100 && (qi.getExclusiveConsumerTag() == null || qi.getExclusiveConsumerTag().equals(""))) { Thread.sleep(100); qi = this.template.getClient().getQueue("/", queue1.getName()); } Queue queueOut = this.template.getQueue("/", queue1.getName()); assertFalse(queueOut.isDurable()); assertFalse(queueOut.isExclusive()); assertTrue(queueOut.isAutoDelete()); assertEquals(queue1.getName(), queueOut.getName()); assertEquals(args, queueOut.getArguments()); assertEquals(consumer, qi.getExclusiveConsumerTag()); channel.basicCancel(consumer); channel.close(); queueOut = this.template.getQueue("/", queue2.getName()); assertTrue(queueOut.isDurable()); assertFalse(queueOut.isExclusive()); assertFalse(queueOut.isAutoDelete()); assertEquals(queue2.getName(), queueOut.getName()); assertEquals(args, queueOut.getArguments()); admin.deleteQueue(queue1.getName()); admin.deleteQueue(queue2.getName()); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests2.java
License:Apache License
@Test public void test36Methods() throws Exception { this.templateWithConfirmsEnabled.convertAndSend(ROUTE, "foo"); this.templateWithConfirmsEnabled.convertAndSend(ROUTE, "foo"); assertMessageCountEquals(2L);//from ww w . j a v a2 s.com assertEquals(Long.valueOf(1), this.templateWithConfirmsEnabled.execute(channel -> { final CountDownLatch latch = new CountDownLatch(2); String consumerTag = channel.basicConsume(ROUTE, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { latch.countDown(); } }); long consumerCount = channel.consumerCount(ROUTE); assertTrue(latch.await(10, TimeUnit.SECONDS)); channel.basicCancel(consumerTag); return consumerCount; })); assertMessageCountEquals(0L); }
From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderCleanerTests.java
License:Apache License
@Test public void testCleanStream() { final RabbitBindingCleaner cleaner = new RabbitBindingCleaner(); final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest", "guest"); final String stream1 = UUID.randomUUID().toString(); String stream2 = stream1 + "-1"; String firstQueue = null;/* w w w. j av a 2 s . c om*/ for (int i = 0; i < 5; i++) { String queue1Name = MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX, BinderUtils.constructPipeName(stream1, i)); String queue2Name = MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX, BinderUtils.constructPipeName(stream2, i)); if (firstQueue == null) { firstQueue = queue1Name; } URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri(); template.put(uri, new AmqpQueue(false, true)); uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri(); template.put(uri, new AmqpQueue(false, true)); uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") .pathSegment("{vhost}", "{queue}") .buildAndExpand("/", MessageChannelBinderSupport.constructDLQName(queue1Name)).encode().toUri(); template.put(uri, new AmqpQueue(false, true)); } CachingConnectionFactory connectionFactory = test.getResource(); RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); final FanoutExchange fanout1 = new FanoutExchange(MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX, MessageChannelBinderSupport.applyPubSub(BinderUtils.constructTapPrefix(stream1) + ".foo.bar"))); rabbitAdmin.declareExchange(fanout1); rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout1)); final FanoutExchange fanout2 = new FanoutExchange(MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX, MessageChannelBinderSupport.applyPubSub(BinderUtils.constructTapPrefix(stream2) + ".foo.bar"))); rabbitAdmin.declareExchange(fanout2); rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout2)); new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() { @Override public Void doInRabbit(Channel channel) throws Exception { String queueName = MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX, BinderUtils.constructPipeName(stream1, 4)); String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel)); try { waitForConsumerStateNot(queueName, 0); cleaner.clean(stream1, false); fail("Expected exception"); } catch (RabbitAdminException e) { assertEquals("Queue " + queueName + " is in use", e.getMessage()); } channel.basicCancel(consumerTag); waitForConsumerStateNot(queueName, 1); try { cleaner.clean(stream1, false); fail("Expected exception"); } catch (RabbitAdminException e) { assertThat(e.getMessage(), startsWith("Cannot delete exchange " + fanout1.getName() + "; it has bindings:")); } return null; } private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException { int n = 0; URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues") .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri(); while (n++ < 100) { @SuppressWarnings("unchecked") Map<String, Object> queueInfo = template.getForObject(uri, Map.class); if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) { break; } Thread.sleep(100); } assertTrue("Consumer state remained at " + state + " after 10 seconds", n < 100); } }); rabbitAdmin.deleteExchange(fanout1.getName()); // easier than deleting the binding rabbitAdmin.declareExchange(fanout1); connectionFactory.destroy(); Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false); assertEquals(2, cleanedMap.size()); List<String> cleanedQueues = cleanedMap.get("queues"); // should *not* clean stream2 assertEquals(10, cleanedQueues.size()); for (int i = 0; i < 5; i++) { assertEquals(BINDER_PREFIX + stream1 + "." + i, cleanedQueues.get(i * 2)); assertEquals(BINDER_PREFIX + stream1 + "." + i + ".dlq", cleanedQueues.get(i * 2 + 1)); } List<String> cleanedExchanges = cleanedMap.get("exchanges"); assertEquals(1, cleanedExchanges.size()); assertEquals(fanout1.getName(), cleanedExchanges.get(0)); // wild card *should* clean stream2 cleanedMap = cleaner.clean(stream1 + "*", false); assertEquals(2, cleanedMap.size()); cleanedQueues = cleanedMap.get("queues"); assertEquals(5, cleanedQueues.size()); for (int i = 0; i < 5; i++) { assertEquals(BINDER_PREFIX + stream2 + "." + i, cleanedQueues.get(i)); } cleanedExchanges = cleanedMap.get("exchanges"); assertEquals(1, cleanedExchanges.size()); assertEquals(fanout2.getName(), cleanedExchanges.get(0)); }