List of usage examples for com.rabbitmq.client Channel close
@Override void close() throws IOException, TimeoutException;
From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java
License:Apache License
@Test public void testWithConnectionFactoryCachedConnectionAndChannels() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock( com.rabbitmq.client.ConnectionFactory.class); final List<com.rabbitmq.client.Connection> mockConnections = new ArrayList<com.rabbitmq.client.Connection>(); final List<Channel> mockChannels = new ArrayList<Channel>(); doAnswer(new Answer<com.rabbitmq.client.Connection>() { private int connectionNumber; @Override//from w ww. j ava2 s . co m public com.rabbitmq.client.Connection answer(InvocationOnMock invocation) throws Throwable { com.rabbitmq.client.Connection connection = mock(com.rabbitmq.client.Connection.class); doAnswer(new Answer<Channel>() { private int channelNumber; @Override public Channel answer(InvocationOnMock invocation) throws Throwable { Channel channel = mock(Channel.class); when(channel.isOpen()).thenReturn(true); int channelNumnber = ++this.channelNumber; when(channel.toString()) .thenReturn("mockChannel" + connectionNumber + ":" + channelNumnber); mockChannels.add(channel); return channel; } }).when(connection).createChannel(); int connectionNumber = ++this.connectionNumber; when(connection.toString()).thenReturn("mockConnection" + connectionNumber); when(connection.isOpen()).thenReturn(true); mockConnections.add(connection); return connection; } }).when(mockConnectionFactory).newConnection((ExecutorService) null); CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory); ccf.setCacheMode(CacheMode.CONNECTION); ccf.setConnectionCacheSize(2); ccf.setChannelCacheSize(2); ccf.afterPropertiesSet(); Set<?> openConnections = TestUtils.getPropertyValue(ccf, "openConnections", Set.class); assertEquals(0, openConnections.size()); BlockingQueue<?> idleConnections = TestUtils.getPropertyValue(ccf, "idleConnections", BlockingQueue.class); assertEquals(0, idleConnections.size()); @SuppressWarnings("unchecked") Map<?, List<?>> cachedChannels = TestUtils.getPropertyValue(ccf, "openConnectionNonTransactionalChannels", Map.class); final AtomicReference<Connection> createNotification = new AtomicReference<Connection>(); final AtomicReference<Connection> closedNotification = new AtomicReference<Connection>(); ccf.setConnectionListeners(Collections.singletonList(new ConnectionListener() { @Override public void onCreate(Connection connection) { assertNull(createNotification.get()); createNotification.set(connection); } @Override public void onClose(Connection connection) { assertNull(closedNotification.get()); closedNotification.set(connection); } })); Connection con1 = ccf.createConnection(); verifyConnectionIs(mockConnections.get(0), con1); assertEquals(1, openConnections.size()); assertEquals(0, idleConnections.size()); assertNotNull(createNotification.get()); assertSame(mockConnections.get(0), targetDelegate(createNotification.getAndSet(null))); Channel channel1 = con1.createChannel(false); verifyChannelIs(mockChannels.get(0), channel1); channel1.close(); //AMQP-358 verify(mockChannels.get(0), never()).close(); con1.close(); // should be ignored, and placed into connection cache. verify(mockConnections.get(0), never()).close(); assertEquals(1, openConnections.size()); assertEquals(1, idleConnections.size()); assertEquals(1, cachedChannels.get(con1).size()); assertNull(closedNotification.get()); /* * will retrieve same connection that was just put into cache, and reuse single channel from cache as well */ Connection con2 = ccf.createConnection(); verifyConnectionIs(mockConnections.get(0), con2); Channel channel2 = con2.createChannel(false); verifyChannelIs(mockChannels.get(0), channel2); channel2.close(); verify(mockChannels.get(0), never()).close(); con2.close(); verify(mockConnections.get(0), never()).close(); assertEquals(1, openConnections.size()); assertEquals(1, idleConnections.size()); assertNull(createNotification.get()); /* * Now check for multiple connections/channels */ con1 = ccf.createConnection(); verifyConnectionIs(mockConnections.get(0), con1); con2 = ccf.createConnection(); verifyConnectionIs(mockConnections.get(1), con2); channel1 = con1.createChannel(false); verifyChannelIs(mockChannels.get(0), channel1); channel2 = con2.createChannel(false); verifyChannelIs(mockChannels.get(1), channel2); assertEquals(2, openConnections.size()); assertEquals(0, idleConnections.size()); assertNotNull(createNotification.get()); assertSame(mockConnections.get(1), targetDelegate(createNotification.getAndSet(null))); // put mock1 in cache channel1.close(); verify(mockChannels.get(1), never()).close(); con1.close(); verify(mockConnections.get(0), never()).close(); assertEquals(2, openConnections.size()); assertEquals(1, idleConnections.size()); assertNull(closedNotification.get()); Connection con3 = ccf.createConnection(); assertNull(createNotification.get()); verifyConnectionIs(mockConnections.get(0), con3); Channel channel3 = con3.createChannel(false); verifyChannelIs(mockChannels.get(0), channel3); assertEquals(2, openConnections.size()); assertEquals(0, idleConnections.size()); channel2.close(); con2.close(); assertEquals(2, openConnections.size()); assertEquals(1, idleConnections.size()); channel3.close(); con3.close(); assertEquals(2, openConnections.size()); assertEquals(2, idleConnections.size()); assertEquals(1, cachedChannels.get(con1).size()); assertEquals(1, cachedChannels.get(con2).size()); /* * Cache size is 2; neither should have been a real close. * con2 (mock2) and con1 should still be in the cache. */ verify(mockConnections.get(0), never()).close(30000); assertNull(closedNotification.get()); verify(mockChannels.get(1), never()).close(); verify(mockConnections.get(1), never()).close(30000); verify(mockChannels.get(1), never()).close(); assertEquals(2, idleConnections.size()); Iterator<?> iterator = idleConnections.iterator(); verifyConnectionIs(mockConnections.get(1), iterator.next()); verifyConnectionIs(mockConnections.get(0), iterator.next()); /* * Now a closed cached connection */ when(mockConnections.get(1).isOpen()).thenReturn(false); con3 = ccf.createConnection(); assertNotNull(closedNotification.get()); assertSame(mockConnections.get(1), targetDelegate(closedNotification.getAndSet(null))); verifyConnectionIs(mockConnections.get(0), con3); assertNull(createNotification.get()); assertEquals(1, openConnections.size()); assertEquals(0, idleConnections.size()); channel3 = con3.createChannel(false); verifyChannelIs(mockChannels.get(0), channel3); channel3.close(); con3.close(); assertNull(closedNotification.get()); assertEquals(1, openConnections.size()); assertEquals(1, idleConnections.size()); /* * Now a closed cached connection when creating a channel */ con3 = ccf.createConnection(); verifyConnectionIs(mockConnections.get(0), con3); assertNull(createNotification.get()); assertEquals(1, openConnections.size()); assertEquals(0, idleConnections.size()); when(mockConnections.get(0).isOpen()).thenReturn(false); channel3 = con3.createChannel(false); assertNotNull(closedNotification.getAndSet(null)); assertNotNull(createNotification.getAndSet(null)); verifyChannelIs(mockChannels.get(2), channel3); channel3.close(); con3.close(); assertNull(closedNotification.get()); assertEquals(1, openConnections.size()); assertEquals(1, idleConnections.size()); Connection con4 = ccf.createConnection(); assertSame(con3, con4); assertEquals(0, idleConnections.size()); Channel channelA = con4.createChannel(false); Channel channelB = con4.createChannel(false); Channel channelC = con4.createChannel(false); channelA.close(); assertEquals(1, cachedChannels.get(con4).size()); channelB.close(); assertEquals(2, cachedChannels.get(con4).size()); channelC.close(); assertEquals(2, cachedChannels.get(con4).size()); // destroy ccf.destroy(); assertNotNull(closedNotification.get()); // physical wasn't invoked, because this mockConnection marked with 'false' for 'isOpen()' verify(mockConnections.get(0), never()).close(30000); verify(mockConnections.get(1), never()).close(30000); verify(mockConnections.get(2)).close(30000); }
From source file:org.springframework.amqp.rabbit.connection.ClientRecoveryCompatibilityTests.java
License:Apache License
@Test public void testDefeatRecovery() throws Exception { final Channel channel1 = mock(Channel.class); when(channel1.isOpen()).thenReturn(true); final Channel channel2 = mock(Channel.class); when(channel2.isOpen()).thenReturn(true); final com.rabbitmq.client.Connection rabbitConn = mock(AutorecoveringConnection.class); when(rabbitConn.isOpen()).thenReturn(true); com.rabbitmq.client.ConnectionFactory cf = mock(com.rabbitmq.client.ConnectionFactory.class); doAnswer(invocation -> rabbitConn).when(cf).newConnection(any(ExecutorService.class), anyString()); when(rabbitConn.createChannel()).thenReturn(channel1).thenReturn(channel2); CachingConnectionFactory ccf = new CachingConnectionFactory(cf); Connection conn1 = ccf.createConnection(); Channel channel = conn1.createChannel(false); verifyChannelIs(channel1, channel);//from ww w .j a va 2 s. c o m channel.close(); conn1.close(); Connection conn2 = ccf.createConnection(); assertSame(conn1, conn2); channel = conn1.createChannel(false); verifyChannelIs(channel1, channel); channel.close(); conn2.close(); when(rabbitConn.isOpen()).thenReturn(false).thenReturn(true); when(channel1.isOpen()).thenReturn(false); conn2 = ccf.createConnection(); try { conn2.createChannel(false); fail("Expected AutoRecoverConnectionNotCurrentlyOpenException"); } catch (AutoRecoverConnectionNotCurrentlyOpenException e) { assertThat(e.getMessage(), equalTo("Auto recovery connection is not currently open")); } channel = conn2.createChannel(false); verifyChannelIs(channel2, channel); channel.close(); verify(rabbitConn, never()).close(); verify(channel1).close(); // physically closed to defeat recovery }
From source file:org.springframework.amqp.rabbit.connection.RabbitResourceHolder.java
License:Apache License
public void closeAll() { for (Channel channel : this.channels) { try {//from www .java 2 s .c o m if (channel != ConsumerChannelRegistry.getConsumerChannel()) { channel.close(); } else { if (logger.isDebugEnabled()) { logger.debug("Skipping close of consumer channel: " + channel.toString()); } } } catch (Throwable ex) { logger.debug("Could not close synchronized Rabbit Channel after transaction", ex); } } for (Connection con : this.connections) { RabbitUtils.closeConnection(con); } this.connections.clear(); this.channels.clear(); this.channelsPerConnection.clear(); }
From source file:org.springframework.amqp.rabbit.connection.RabbitUtils.java
License:Apache License
/** * Close the given RabbitMQ Channel and ignore any thrown exception. This is useful for typical <code>finally</code> * blocks in manual RabbitMQ code.//from w w w.j ava 2 s.c o m * @param channel the RabbitMQ Channel to close (may be <code>null</code>) */ public static void closeChannel(Channel channel) { if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException ex) { logger.debug("Could not close RabbitMQ Channel", ex); } catch (ShutdownSignalException sig) { if (!isNormalShutdown(sig)) { logger.debug("Unexpected exception on closing RabbitMQ Channel", sig); } } catch (Throwable ex) { logger.debug("Unexpected exception on closing RabbitMQ Channel", ex); } } }
From source file:org.springframework.amqp.rabbit.connection.RabbitUtils.java
License:Apache License
public static boolean isNormalChannelClose(ShutdownSignalException sig) { Object shutdownReason = determineShutdownReason(sig); return shutdownReason instanceof AMQP.Channel.Close && AMQP.REPLY_SUCCESS == ((AMQP.Channel.Close) shutdownReason).getReplyCode() && "OK".equals(((AMQP.Channel.Close) shutdownReason).getReplyText()); }
From source file:org.springframework.amqp.rabbit.connection.SSLConnectionTests.java
License:Apache License
@Test @Ignore//from w w w . jav a 2s . c om public void test() throws Exception { RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean(); fb.setUseSSL(true); fb.setSslPropertiesLocation(new ClassPathResource("ssl.properties")); fb.setClientProperties(Collections.<String, Object>singletonMap("foo", "bar")); fb.afterPropertiesSet(); ConnectionFactory cf = fb.getObject(); assertEquals("bar", cf.getClientProperties().get("foo")); Connection conn = cf.newConnection(); Channel chan = conn.createChannel(); chan.close(); conn.close(); }
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 {/* w ww .j a v a2 s . 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();//from w w w .j a v a 2 s . co 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.RabbitTemplatePublisherCallbacksIntegrationTests3.java
License:Apache License
@Test public void testDeferredChannelCacheNack() throws Exception { final CachingConnectionFactory cf = new CachingConnectionFactory( RabbitAvailableCondition.getBrokerRunning().getConnectionFactory()); cf.setPublisherReturns(true);//w ww . j a va 2 s . c om cf.setPublisherConfirms(true); final RabbitTemplate template = new RabbitTemplate(cf); final CountDownLatch returnLatch = new CountDownLatch(1); final CountDownLatch confirmLatch = new CountDownLatch(1); final AtomicInteger cacheCount = new AtomicInteger(); template.setConfirmCallback((cd, a, c) -> { cacheCount.set(TestUtils.getPropertyValue(cf, "cachedChannelsNonTransactional", List.class).size()); confirmLatch.countDown(); }); template.setReturnCallback((m, r, rt, e, rk) -> { returnLatch.countDown(); }); template.setMandatory(true); Connection conn = cf.createConnection(); Channel channel1 = conn.createChannel(false); Channel channel2 = conn.createChannel(false); channel1.close(); channel2.close(); conn.close(); assertThat(TestUtils.getPropertyValue(cf, "cachedChannelsNonTransactional", List.class).size()) .isEqualTo(2); template.convertAndSend("", QUEUE2 + "junk", "foo", new MyCD("foo")); assertThat(returnLatch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(confirmLatch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(cacheCount.get()).isEqualTo(1); cf.destroy(); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests3.java
License:Apache License
@Test public void testDeferredChannelCacheAck() throws Exception { final CachingConnectionFactory cf = new CachingConnectionFactory( RabbitAvailableCondition.getBrokerRunning().getConnectionFactory()); cf.setPublisherConfirms(true);//from w w w . ja v a 2 s . c om final RabbitTemplate template = new RabbitTemplate(cf); final CountDownLatch confirmLatch = new CountDownLatch(1); final AtomicInteger cacheCount = new AtomicInteger(); template.setConfirmCallback((cd, a, c) -> { cacheCount.set(TestUtils.getPropertyValue(cf, "cachedChannelsNonTransactional", List.class).size()); confirmLatch.countDown(); }); template.setMandatory(true); Connection conn = cf.createConnection(); Channel channel1 = conn.createChannel(false); Channel channel2 = conn.createChannel(false); channel1.close(); channel2.close(); conn.close(); assertThat(TestUtils.getPropertyValue(cf, "cachedChannelsNonTransactional", List.class).size()) .isEqualTo(2); template.convertAndSend("", QUEUE2, "foo", new MyCD("foo")); assertThat(confirmLatch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(cacheCount.get()).isEqualTo(1); cf.destroy(); }