@Override public synchronized void start() { if (!this.running) { if (!this.lazyConnect && this.connectionFactory != null) { try { Connection connection = this.connectionFactory.createConnection(); // NOSONAR (close) if (connection != null) { connection.close(); } } catch (RuntimeException e) { logger.error("Failed to eagerly establish the connection.", e); } } doStart(); this.running = true; } }
@Override public void handleRecovery(Recoverable recoverable) { try { connection.close(); } catch (Exception e) { AbstractConnectionFactory.this.logger.error("Failed to close auto-recover connection", e); } }
@Override public void handleRecovery(Recoverable recoverable) { try { connection.close(); } catch (Exception e) { AbstractConnectionFactory.this.logger.error("Failed to close auto-recover connection", e); } }
/** * Close the given RabbitMQ Connection and ignore any thrown exception. This is useful for typical * <code>finally</code> blocks in manual RabbitMQ code. * @param connection the RabbitMQ Connection to close (may be <code>null</code>) */ public static void closeConnection(@Nullable Connection connection) { if (connection != null) { try { connection.close(); } catch (AlreadyClosedException ace) { // empty } catch (Exception ex) { logger.debug("Ignoring Connection exception - assuming already closed: " + ex.getMessage(), ex); } } }
/** * Close the given RabbitMQ Connection and ignore any thrown exception. This is useful for typical * <code>finally</code> blocks in manual RabbitMQ code. * @param connection the RabbitMQ Connection to close (may be <code>null</code>) */ public static void closeConnection(@Nullable Connection connection) { if (connection != null) { try { connection.close(); } catch (AlreadyClosedException ace) { // empty } catch (Exception ex) { logger.debug("Ignoring Connection exception - assuming already closed: " + ex.getMessage(), ex); } } }
@Override protected void obtainResource() throws Exception { resource = new CachingConnectionFactory("localhost"); resource.createConnection().close(); if (management) { Socket socket = SocketFactory.getDefault().createSocket("localhost", 15672); socket.close(); } }
@Override protected void obtainResource() throws Exception { resource = new CachingConnectionFactory("localhost"); resource.createConnection().close(); if (management) { Socket socket = SocketFactory.getDefault().createSocket("localhost", 15672); socket.close(); } }
@Override public synchronized void start() { if (!this.running) { if (!this.lazyConnect && this.connectionFactory != null) { try { Connection connection = this.connectionFactory.createConnection(); // NOSONAR (close) if (connection != null) { connection.close(); } } catch (RuntimeException e) { logger.error("Failed to eagerly establish the connection.", e); } } doStart(); this.running = true; } }
@Override public void onMessage(Message message, Channel channel) throws Exception { String value = new String(message.getBody()); logger.debug("Receiving: " + value); if (failed.compareAndSet(false, true)) { // intentional error (causes exception on connection thread): connection.close(); } else { latch.countDown(); } } }
protected void checkMismatchedQueues() { if (this.mismatchedQueuesFatal && this.amqpAdmin != null) { try { this.amqpAdmin.initialize(); } catch (AmqpConnectException e) { logger.info("Broker not available; cannot check queue declarations"); } catch (AmqpIOException e) { if (RabbitUtils.isMismatchedQueueArgs(e)) { throw new FatalListenerStartupException("Mismatched queues", e); } else { logger.info("Failed to get connection during start(): " + e); } } } else { try { Connection connection = getConnectionFactory().createConnection(); // NOSONAR if (connection != null) { connection.close(); } } catch (Exception e) { logger.info("Broker not available; cannot force queue declarations during start"); } } }
@Test public void customQueueIsUsedIfProvided() throws Exception { this.applicationContext.getBean(SingleConnectionFactory.class).createConnection().close(); Logger log = (Logger) LoggerFactory.getLogger("customQueue"); String testMessage = String.valueOf(ThreadLocalRandom.current().nextLong()); log.info(testMessage); BlockingQueue<AmqpAppender.Event> appenderQueue = ((CustomQueueAppender) log.getAppender("AMQPWithCustomQueue")).mockedQueue; verify(appenderQueue).add(argThat(arg -> arg.getEvent().getMessage().equals(testMessage))); }
@Test public void testWithChannelListener() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); when(mockConnection.createChannel()).thenReturn(mockChannel); final AtomicInteger called = new AtomicInteger(0); AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory); connectionFactory.setChannelListeners(Collections.singletonList( (channel, transactional) -> called.incrementAndGet())); Connection con = connectionFactory.createConnection(); Channel channel = con.createChannel(false); assertEquals(1, called.get()); channel.close(); con.close(); verify(mockConnection, never()).close(); connectionFactory.createConnection(); con.createChannel(false); assertEquals(2, called.get()); connectionFactory.destroy(); verify(mockConnection, atLeastOnce()).close(anyInt()); verify(mockConnectionFactory).newConnection(any(ExecutorService.class), anyString()); }
channel.close(); RabbitUtils.setPhysicalCloseRequired(channel, false); con.close(); // should be ignored
@Test public void connectionName() { Connection conn = this.connectionFactory.createConnection(); conn.close(); assertThat(conn.getDelegate().getClientProvidedName(), equalTo("testConnectionName")); }
@Test public void testWithConnectionFactoryDefaults() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())).thenReturn(mockConnection); when(mockConnection.createChannel()).thenReturn(mockChannel); when(mockChannel.isOpen()).thenReturn(true); when(mockConnection.isOpen()).thenReturn(true); CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory); ccf.setExecutor(mock(ExecutorService.class)); Connection con = ccf.createConnection(); Channel channel = con.createChannel(false); channel.close(); // should be ignored, and placed into channel cache. con.close(); // should be ignored Connection con2 = ccf.createConnection(); /* * will retrieve same channel object that was just put into channel cache */ Channel channel2 = con2.createChannel(false); channel2.close(); // should be ignored con2.close(); // should be ignored assertSame(con, con2); assertSame(channel, channel2); verify(mockConnection, never()).close(); verify(mockChannel, never()).close(); }
@Test public void testWithListenerRegisteredAfterOpen() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())).thenReturn(mockConnection); final AtomicInteger called = new AtomicInteger(0); AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory); Connection con = connectionFactory.createConnection(); assertEquals(0, called.get()); connectionFactory.setConnectionListeners(Collections.singletonList(new ConnectionListener() { @Override public void onCreate(Connection connection) { called.incrementAndGet(); } @Override public void onClose(Connection connection) { called.decrementAndGet(); } })); assertEquals(1, called.get()); con.close(); assertEquals(1, called.get()); verify(mockConnection, never()).close(anyInt()); connectionFactory.createConnection(); assertEquals(1, called.get()); connectionFactory.destroy(); assertEquals(0, called.get()); verify(mockConnection, atLeastOnce()).close(anyInt()); verify(mockConnectionFactory, times(1)).newConnection(any(ExecutorService.class), anyString()); }
channel1.close(); channel2.close(); conn.close(); assertThat(TestUtils.getPropertyValue(cf, "cachedChannelsNonTransactional", List.class).size()).isEqualTo(2); template.convertAndSend("", QUEUE2 + "junk", "foo", new MyCD("foo"));
@Test public void testDeferredChannelCacheAck() throws Exception { final CachingConnectionFactory cf = new CachingConnectionFactory( RabbitAvailableCondition.getBrokerRunning().getConnectionFactory()); cf.setPublisherConfirms(true); 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(); }
@Test public void testPublisherConnection() throws Exception { com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(com.rabbitmq.client.ConnectionFactory.class); com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())).thenReturn(mockConnection); when(mockConnection.createChannel()).thenReturn(mockChannel); when(mockChannel.isOpen()).thenReturn(true); when(mockConnection.isOpen()).thenReturn(true); CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory); ccf.setExecutor(mock(ExecutorService.class)); Connection con = ccf.getPublisherConnectionFactory().createConnection(); Channel channel = con.createChannel(false); channel.close(); // should be ignored, and placed into channel cache. con.close(); // should be ignored Connection con2 = ccf.getPublisherConnectionFactory().createConnection(); /* * will retrieve same channel object that was just put into channel cache */ Channel channel2 = con2.createChannel(false); channel2.close(); // should be ignored con2.close(); // should be ignored assertSame(con, con2); assertSame(channel, channel2); verify(mockConnection, never()).close(); verify(mockChannel, never()).close(); assertNull(TestUtils.getPropertyValue(ccf, "connection.target")); assertNotNull(TestUtils.getPropertyValue(ccf, "publisherConnectionFactory.connection.target")); assertSame(con, TestUtils.getPropertyValue(ccf, "publisherConnectionFactory.connection")); }
@Test public void testWithEncoder() { this.applicationContext.getBean(SingleConnectionFactory.class).createConnection().close(); Logger log = (Logger) LoggerFactory.getLogger("encoded"); log.info("foo"); log.info("bar"); Message received = this.template.receive(this.encodedQueue.getName()); assertNotNull(received); assertThat(new String(received.getBody()), containsString("%d %p %t [%c] - <%m>%n")); assertThat(received.getMessageProperties().getAppId(), equalTo("AmqpAppenderTest")); assertNotNull(this.template.receive(this.encodedQueue.getName())); assertThat(new String(this.template.receive(this.encodedQueue.getName()).getBody()), not(containsString("%d %p %t [%c] - <%m>%n"))); }