List of usage examples for com.rabbitmq.client Connection createChannel
Channel createChannel() throws IOException;
From source file:reactor.rabbitmq.ConnectionRecoveryTests.java
License:Open Source License
@Test void consumeAutoAckRetryOnAck() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection()).thenReturn(mockConnection); when(mockConnection.createChannel()).thenReturn(mockChannel); CountDownLatch consumerRegisteredLatch = new CountDownLatch(1); AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>(); when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class), any(CancelCallback.class))).thenAnswer(answer -> { deliverCallbackAtomicReference.set(answer.getArgument(2)); consumerRegisteredLatch.countDown(); return "ctag"; });/* w w w .j a v a2s .c o m*/ AtomicLong ackCount = new AtomicLong(0); AtomicLong errorAck = new AtomicLong(0); doAnswer(answer -> { ackCount.incrementAndGet(); if (ackCount.get() == 3 || ackCount.get() == 4) { errorAck.incrementAndGet(); throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null)); } return null; }).when(mockChannel).basicAck(anyLong(), anyBoolean()); receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection)); AtomicInteger ackedMessages = new AtomicInteger(0); receiver.consumeAutoAck("whatever", new ConsumeOptions().exceptionHandler(new ExceptionHandlers.RetryAcknowledgmentExceptionHandler( ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE))) .subscribe(msg -> { ackedMessages.incrementAndGet(); }); assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS), "Consumer should have been registered by now"); int nbMessages = 10; IntStream.range(0, nbMessages).forEach(i -> { try { deliverCallbackAtomicReference.get().handle("", new Delivery(new Envelope(i, true, null, null), null, null)); } catch (IOException e) { throw new RuntimeException(e); } }); assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried"); assertEquals(nbMessages + errorAck.get(), ackCount.get(), "There should have been nbMessages+ackInError calls to basicAck as acknowledgments are retried"); }
From source file:reactor.rabbitmq.ConnectionRecoveryTests.java
License:Open Source License
@Test void consumeManualAckRetryOnAck() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection()).thenReturn(mockConnection); when(mockConnection.createChannel()).thenReturn(mockChannel); CountDownLatch consumerRegisteredLatch = new CountDownLatch(1); AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>(); when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class), any(CancelCallback.class))).thenAnswer(answer -> { deliverCallbackAtomicReference.set(answer.getArgument(2)); consumerRegisteredLatch.countDown(); return "ctag"; });/* w w w. jav a 2 s. c om*/ AtomicLong ackCount = new AtomicLong(0); doAnswer(answer -> { ackCount.incrementAndGet(); if (ackCount.get() == 3 || ackCount.get() == 4) { throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null)); } return null; }).when(mockChannel).basicAck(anyLong(), anyBoolean()); receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection)); AtomicInteger ackedMessages = new AtomicInteger(0); BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = new ExceptionHandlers.RetryAcknowledgmentExceptionHandler( ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE); receiver.consumeManualAck("whatever", new ConsumeOptions().exceptionHandler(exceptionHandler)) .subscribe(msg -> { // do business stuff // ... // trying to ack msg.ack(); ackedMessages.incrementAndGet(); }); assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS), "Consumer should have been registered by now"); int nbMessages = 10; IntStream.range(0, nbMessages).forEach(i -> { try { deliverCallbackAtomicReference.get().handle("", new Delivery(new Envelope(i, true, null, null), null, null)); } catch (IOException e) { throw new RuntimeException(e); } }); assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried"); }
From source file:reactor.rabbitmq.LazyChannelPool.java
License:Open Source License
private Channel createChannel(Connection connection) { try {//from w ww. j a v a 2s . c om return connection.createChannel(); } catch (IOException e) { throw new RabbitFluxException("Error while creating channel", e); } }
From source file:reactor.rabbitmq.RabbitFluxTests.java
License:Open Source License
@ParameterizedTest @MethodSource("noAckAndManualAckFluxArguments") public void receiverQueueDeleted(BiFunction<Receiver, String, Flux<? extends Delivery>> fluxFactory) throws Exception { // given//from ww w . ja v a 2s . co m Channel channel = connection.createChannel(); Channel channelSpy = spy(channel); Connection mockConnection = mock(Connection.class); when(mockConnection.createChannel()).thenReturn(channelSpy); CountDownLatch latch = new CountDownLatch(1); channel.basicPublish("", queue, null, "Hello".getBytes()); receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionMono(Mono.just(mockConnection))); fluxFactory.apply(receiver, queue).subscribe(delivery -> { latch.countDown(); }); assertTrue(latch.await(1, TimeUnit.SECONDS)); // when channel.queueDelete(queue); // calls CancelCallback, consumerTag is unknown // then verify(channelSpy, never()).basicCancel(anyString()); }
From source file:reactor.rabbitmq.RabbitFluxTests.java
License:Open Source License
@ParameterizedTest @MethodSource("noAckAndManualAckFluxArguments") public void receiverOnDispose(BiFunction<Receiver, String, Flux<? extends Delivery>> fluxFactory) throws Exception { // given//from www.j a v a 2 s.co m Channel channel = connection.createChannel(); Channel channelSpy = spy(channel); Connection mockConnection = mock(Connection.class); when(mockConnection.createChannel()).thenReturn(channelSpy); CountDownLatch latch = new CountDownLatch(1); channel.basicPublish("", queue, null, "Hello".getBytes()); receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionMono(Mono.just(mockConnection))); Disposable subscription = fluxFactory.apply(receiver, queue).subscribe(delivery -> { latch.countDown(); }); assertTrue(latch.await(1, TimeUnit.SECONDS)); // when subscription.dispose(); // then verify(channelSpy).basicCancel(anyString()); }
From source file:reactor.rabbitmq.RabbitFluxTests.java
License:Open Source License
@Test public void senderRetryCreateChannel() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); when(mockConnectionFactory.newConnection()).thenReturn(mockConnection); when(mockConnection.createChannel()).thenThrow(new IOException("already closed exception")) .thenThrow(new IOException("already closed exception")).thenReturn(connection.createChannel()); int nbMessages = 10; Flux<OutboundMessage> msgFlux = Flux.range(0, nbMessages) .map(i -> new OutboundMessage("", queue, "".getBytes())); sender = createSender(new SenderOptions().connectionFactory(mockConnectionFactory)); StepVerifier.create(sender.send(msgFlux).retry(2)).verifyComplete(); verify(mockConnection, times(3)).createChannel(); StepVerifier.create(consume(queue, nbMessages)).expectNextCount(nbMessages).verifyComplete(); }
From source file:reactor.rabbitmq.RabbitFluxTests.java
License:Open Source License
@Test public void senderRetryNotWorkingWhenCreateChannelIsCached() throws Exception { int nbMessages = 10; Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnection.createChannel()).thenThrow(new RuntimeException("already closed exception")) .thenThrow(new RuntimeException("already closed exception")).thenReturn(mockChannel); Flux<OutboundMessage> msgFlux = Flux.range(0, nbMessages) .map(i -> new OutboundMessage("", queue, "".getBytes())); SenderOptions senderOptions = new SenderOptions() .channelMono(Mono.just(mockConnection).map(this::createChannel).cache()); sender = createSender(senderOptions); StepVerifier.create(sender.send(msgFlux).retry(2)).expectError(RabbitFluxException.class).verify(); verify(mockChannel, never()).basicPublish(anyString(), anyString(), any(AMQP.BasicProperties.class), any(byte[].class)); verify(mockChannel, never()).close(); }
From source file:reactor.rabbitmq.RabbitFluxTests.java
License:Open Source License
@Test public void publishConfirmsErrorWhilePublishing() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection()).thenReturn(mockConnection); when(mockConnection.createChannel()).thenReturn(mockChannel); when(mockConnection.isOpen()).thenReturn(true); when(mockChannel.getConnection()).thenReturn(mockConnection); AtomicLong publishSequence = new AtomicLong(); when(mockChannel.getNextPublishSeqNo()).thenAnswer(invocation -> publishSequence.incrementAndGet()); when(mockChannel.isOpen()).thenReturn(true); CountDownLatch channelCloseLatch = new CountDownLatch(1); doAnswer(answer -> {//w ww . ja v a 2 s. c o m channelCloseLatch.countDown(); return null; }).when(mockChannel).close(); CountDownLatch serverPublishConfirmLatch = new CountDownLatch(1); doNothing().doAnswer(answer -> { // see https://github.com/reactor/reactor-rabbitmq/pull/67#issuecomment-472789735 serverPublishConfirmLatch.await(5, TimeUnit.SECONDS); throw new IOException("simulated error while publishing"); }).when(mockChannel).basicPublish(anyString(), anyString(), nullable(AMQP.BasicProperties.class), any(byte[].class)); int nbMessages = 10; Flux<OutboundMessage> msgFlux = Flux.range(0, nbMessages) .map(i -> new OutboundMessage("", queue, "".getBytes())); int nbMessagesAckNack = 1 + 1; // first published message confirmed + "fake" confirmation because of sending failure CountDownLatch confirmLatch = new CountDownLatch(nbMessagesAckNack); sender = createSender(new SenderOptions().connectionFactory(mockConnectionFactory)); sender.sendWithPublishConfirms(msgFlux, new SendOptions().exceptionHandler((ctx, e) -> { throw new RabbitFluxException(e); })).subscribe(outboundMessageResult -> { if (outboundMessageResult.getOutboundMessage() != null) { confirmLatch.countDown(); } }, error -> { }); // have to wait a bit the subscription propagates and add the confirm listener Thread.sleep(100L); ArgumentCaptor<ConfirmListener> confirmListenerArgumentCaptor = ArgumentCaptor .forClass(ConfirmListener.class); verify(mockChannel).addConfirmListener(confirmListenerArgumentCaptor.capture()); ConfirmListener confirmListener = confirmListenerArgumentCaptor.getValue(); ExecutorService ioExecutor = Executors.newSingleThreadExecutor(); ioExecutor.submit(() -> { confirmListener.handleAck(1, false); serverPublishConfirmLatch.countDown(); return null; }); assertTrue(confirmLatch.await(1L, TimeUnit.SECONDS)); assertTrue(channelCloseLatch.await(1L, TimeUnit.SECONDS)); verify(mockChannel, times(1)).close(); }
From source file:reactor.rabbitmq.RabbitFluxTests.java
License:Open Source License
private Channel createChannel(Connection connection) { try {/*from ww w . jav a 2 s .co m*/ return connection.createChannel(); } catch (Exception e) { throw new RabbitFluxException(e); } }
From source file:reactor.rabbitmq.ReactorRabbitMqTests.java
License:Open Source License
@Test public void publishConfirmsErrorWhilePublishing() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockConnectionFactory.newConnection()).thenReturn(mockConnection); when(mockConnection.createChannel()).thenReturn(mockChannel); AtomicLong publishSequence = new AtomicLong(); when(mockChannel.getNextPublishSeqNo()).thenAnswer(invocation -> publishSequence.incrementAndGet()); doNothing().doThrow(new IOException("simulated error while publishing")).when(mockChannel) .basicPublish(anyString(), anyString(), any(AMQP.BasicProperties.class), any(byte[].class)); int nbMessages = 10; Flux<OutboundMessage> msgFlux = Flux.range(0, nbMessages) .map(i -> new OutboundMessage("", queue, "".getBytes())); int nbMessagesAckNack = 2; CountDownLatch confirmLatch = new CountDownLatch(nbMessagesAckNack); sender = ReactorRabbitMq.createSender(mockConnectionFactory); CountDownLatch subscriptionLatch = new CountDownLatch(1); sender.sendWithPublishConfirms(msgFlux).subscribe(outboundMessageResult -> confirmLatch.countDown(), error -> {/*from www .ja v a2s . c o m*/ }); // have to wait a bit the subscription propagates and add the confirm listener Thread.sleep(100L); ArgumentCaptor<ConfirmListener> confirmListenerArgumentCaptor = ArgumentCaptor .forClass(ConfirmListener.class); verify(mockChannel).addConfirmListener(confirmListenerArgumentCaptor.capture()); ConfirmListener confirmListener = confirmListenerArgumentCaptor.getValue(); ExecutorService ioExecutor = Executors.newSingleThreadExecutor(); ioExecutor.submit(() -> { confirmListener.handleAck(1, false); return null; }); assertTrue(confirmLatch.await(1L, TimeUnit.SECONDS)); verify(mockChannel, times(1)).close(); }