List of usage examples for com.rabbitmq.client Channel basicCancel
void basicCancel(String consumerTag) throws IOException;
From source file:org.objectweb.proactive.extensions.amqp.remoteobject.AbstractFindQueuesRPCClient.java
License:Open Source License
public final List<URI> discover(URI uri, String exchangeName, long timeout) throws Exception { ReusableChannel reusableChannel = getReusableChannel(uri); try {//from www . j a va 2 s . co m Channel channel = reusableChannel.getChannel(); String replyQueueName = createReplyQueue(channel); QueueingConsumer consumer = new QueueingConsumer(channel); String consumerTag = channel.basicConsume(replyQueueName, true, consumer); List<URI> response = new ArrayList<URI>(); BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName) .type(DISCOVERY_QUEUES_MESSAGE_TYPE).build(); channel.basicPublish(exchangeName, "", props, null); TimeoutAccounter time = TimeoutAccounter.getAccounter(timeout); while (!time.isTimeoutElapsed()) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(200); if (delivery != null) { URI u = URI.create(new String(delivery.getBody())); response.add(u); } } // stop consuming, this also should delete temporary queue channel.basicCancel(consumerTag); reusableChannel.returnChannel(); return response; } catch (Exception e) { reusableChannel.close(); throw e; } }
From source file:org.opendaylight.federationmessagequeue.impl.RabbitMessageBus.java
License:Open Source License
@Override public void detachHandler(String queueName, String consumerTag) { MessageBusConnectionData messageBusConnectionData = queueNameToConnectionData.get(queueName); if (messageBusConnectionData != null) { Channel channel = messageBusConnectionData.channel; try {/*from w w w . j a v a 2 s . c om*/ LOG.info("Cancelling queue handler {} " + consumerTag); channel.basicCancel(consumerTag); } catch (IOException e) { LOG.error("Detaching queue handler failed", e); } } else { LOG.warn("unknown queue name {} couldn't detach handler", queueName); } }
From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java
License:Apache License
@Test public void testWithConnectionListener() throws IOException { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock( com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class); com.rabbitmq.client.Connection mockConnection2 = mock(com.rabbitmq.client.Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection1, mockConnection2);//from w w w . j a va2 s . c om when(mockConnection1.isOpen()).thenReturn(true); when(mockChannel.isOpen()).thenReturn(true); when(mockConnection1.createChannel()).thenReturn(mockChannel); when(mockConnection2.createChannel()).thenReturn(mockChannel); final AtomicReference<Connection> created = new AtomicReference<Connection>(); final AtomicReference<Connection> closed = new AtomicReference<Connection>(); AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory); connectionFactory.addConnectionListener(new ConnectionListener() { @Override public void onCreate(Connection connection) { created.set(connection); } @Override public void onClose(Connection connection) { closed.set(connection); } }); ((CachingConnectionFactory) connectionFactory).setChannelCacheSize(1); Connection con = connectionFactory.createConnection(); Channel channel = con.createChannel(false); assertSame(con, created.get()); channel.close(); con.close(); verify(mockConnection1, never()).close(); Connection same = connectionFactory.createConnection(); channel = con.createChannel(false); assertSame(con, same); channel.close(); when(mockConnection1.isOpen()).thenReturn(false); when(mockChannel.isOpen()).thenReturn(false); // force a connection refresh channel.basicCancel("foo"); channel.close(); Connection notSame = connectionFactory.createConnection(); assertNotSame(con, notSame); assertSame(con, closed.get()); assertSame(notSame, created.get()); connectionFactory.destroy(); verify(mockConnection2, atLeastOnce()).close(anyInt()); assertSame(notSame, closed.get()); verify(mockConnectionFactory, times(2)).newConnection((ExecutorService) null); }
From source file:org.springframework.amqp.rabbit.connection.RabbitUtils.java
License:Apache License
public static void closeMessageConsumer(Channel channel, Collection<String> consumerTags, boolean transactional) { if (!channel.isOpen()) { return;//from w w w .j a v a 2 s .co m } try { synchronized (consumerTags) { for (String consumerTag : consumerTags) { channel.basicCancel(consumerTag); } } if (transactional) { /* * Re-queue in-flight messages if any (after the consumer is cancelled to prevent the broker from simply * sending them back to us). Does not require a tx.commit. */ channel.basicRecover(true); } /* * If not transactional then we are auto-acking (at least as of 1.0.0.M2) so there is nothing to recover. * Messages are going to be lost in general. */ } catch (Exception ex) { throw RabbitExceptionTranslator.convertRabbitAccessException(ex); } }
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();//from ww w.ja v a2 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.support.RabbitUtils.java
License:Apache License
public static void closeMessageConsumer(Channel channel, String consumerTag, boolean transactional) { if (!channel.isOpen()) { return;//from w w w.j ava 2s. c o m } try { channel.basicCancel(consumerTag); if (transactional) { /* * Re-queue in-flight messages if any (after the consumer is cancelled to prevent the broker from simply * sending them back to us). Does not require a tx.commit. */ channel.basicRecover(true); } } catch (Exception ex) { throw convertRabbitAccessException(ex); } }
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;//from w w w . java 2s . 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)); }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleanerTests.java
License:Apache License
@Test public void testCleanStream() { final RabbitBusCleaner cleaner = new RabbitBusCleaner(); final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest", "guest"); final String stream1 = UUID.randomUUID().toString(); String stream2 = stream1 + "-1"; String firstQueue = null;/* ww w .ja va 2 s . c om*/ for (int i = 0; i < 5; i++) { String queue1Name = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.constructPipeName(stream1, i)); String queue2Name = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.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("/", MessageBusSupport.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(MessageBusSupport.applyPrefix(XDBUS_PREFIX, MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(stream1) + ".foo.bar"))); rabbitAdmin.declareExchange(fanout1); rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout1)); final FanoutExchange fanout2 = new FanoutExchange(MessageBusSupport.applyPrefix(XDBUS_PREFIX, MessageBusSupport.applyPubSub(BusUtils.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 = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.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(XDBUS_PREFIX + stream1 + "." + i, cleanedQueues.get(i * 2)); assertEquals(XDBUS_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(XDBUS_PREFIX + stream2 + "." + i, cleanedQueues.get(i)); } cleanedExchanges = cleanedMap.get("exchanges"); assertEquals(1, cleanedExchanges.size()); assertEquals(fanout2.getName(), cleanedExchanges.get(0)); }
From source file:reactor.rabbitmq.Receiver.java
License:Open Source License
public Flux<Delivery> consumeNoAck(final String queue, ReceiverOptions options) { // TODO track flux so it can be disposed when the sender is closed? // could be also developer responsibility return Flux.create(emitter -> { connectionMono.subscribe(connection -> { try { // TODO handle exception Channel channel = connection.createChannel(); final DefaultConsumer consumer = new DefaultConsumer(channel) { @Override/*from w w w .j a va 2s. co m*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { emitter.next(new Delivery(envelope, properties, body)); } @Override public void handleCancel(String consumerTag) throws IOException { LOGGER.warn("Flux consumer {} has been cancelled", consumerTag); } }; final String consumerTag = channel.basicConsume(queue, true, consumer); emitter.onDispose(() -> { try { if (channel.isOpen() && channel.getConnection().isOpen()) { channel.basicCancel(consumerTag); channel.close(); } } catch (TimeoutException | IOException e) { throw new ReactorRabbitMqException(e); } }); } catch (IOException e) { throw new ReactorRabbitMqException(e); } }); }, options.getOverflowStrategy()); }
From source file:reactor.rabbitmq.Receiver.java
License:Open Source License
public Flux<AcknowledgableDelivery> consumeManuelAck(final String queue, ReceiverOptions options) { // TODO track flux so it can be disposed when the sender is closed? // could be also developer responsibility return Flux.create(emitter -> { connectionMono.subscribe(connection -> { try { Channel channel = connection.createChannel(); if (options.getQos() != 0) { channel.basicQos(options.getQos()); }//from w w w.j a va 2 s .c om final DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { AcknowledgableDelivery message = new AcknowledgableDelivery(envelope, properties, body, getChannel()); if (options.getHookBeforeEmit().apply(emitter, message)) { emitter.next(message); } } }; final String consumerTag = channel.basicConsume(queue, false, consumer); emitter.onDispose(() -> { try { if (channel.isOpen() && channel.getConnection().isOpen()) { channel.basicCancel(consumerTag); channel.close(); } } catch (TimeoutException | IOException e) { throw new ReactorRabbitMqException(e); } }); } catch (IOException e) { throw new ReactorRabbitMqException(e); } }); }, options.getOverflowStrategy()); }