Example usage for com.rabbitmq.client Channel basicPublish

List of usage examples for com.rabbitmq.client Channel basicPublish

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel basicPublish.

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
public void topologyRecovery() throws Exception {
    sender = createSender(new SenderOptions().connectionMono(connectionMono));
    String q = UUID.randomUUID().toString();
    String e = UUID.randomUUID().toString();
    sender.declare(QueueSpecification.queue(q).exclusive(true))
            .then(sender.declare(ExchangeSpecification.exchange(e).type("fanout").autoDelete(true)))
            .then(sender.bind(BindingSpecification.binding(e, "", q))).block(Duration.ofSeconds(5));

    Channel ch = connection.createChannel();
    AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
    receiver = createReceiver(new ReceiverOptions().connectionMono(connectionMono));
    receiver.consumeNoAck(q).subscribe(delivery -> latch.get().countDown());

    ch.basicPublish(e, "", null, "".getBytes());

    assertTrue(latch.get().await(5, TimeUnit.SECONDS));

    latch.set(new CountDownLatch(1));

    closeAndWaitForRecovery((RecoverableConnection) connectionMono.block());

    ch.basicPublish(e, "", null, "".getBytes());
    assertTrue(latch.get().await(5, TimeUnit.SECONDS));
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void receiverConsumeNoAck() throws Exception {
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = RabbitFlux.createReceiver();

    for (int $ : IntStream.range(0, 1).toArray()) {
        Flux<Delivery> flux = receiver.consumeNoAck(queue,
                new ConsumeOptions().overflowStrategy(FluxSink.OverflowStrategy.BUFFER));
        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }/*from  w  ww.j a  v  a2s .  com*/

        CountDownLatch latch = new CountDownLatch(nbMessages * 2);
        AtomicInteger counter = new AtomicInteger();
        Disposable subscription = flux.subscribe(msg -> {
            counter.incrementAndGet();
            latch.countDown();
        });

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }

        assertTrue(latch.await(1, TimeUnit.SECONDS));
        subscription.dispose();
        assertEquals(nbMessages * 2, counter.get());
    }
    assertNull(connection.createChannel().basicGet(queue, true));
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void receiverConsumeAutoAck() throws Exception {
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = RabbitFlux.createReceiver();

    for (int $ : IntStream.range(0, 10).toArray()) {
        Flux<Delivery> flux = receiver.consumeAutoAck(queue);

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }/*w w  w. j a v  a  2  s.  c o  m*/

        CountDownLatch latch = new CountDownLatch(nbMessages * 2);
        AtomicInteger counter = new AtomicInteger();
        Disposable subscription = flux.subscribe(msg -> {
            counter.incrementAndGet();
            latch.countDown();
        });

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }

        assertTrue(latch.await(1, TimeUnit.SECONDS));
        subscription.dispose();
        assertEquals(nbMessages * 2, counter.get());
    }

    assertNull(connection.createChannel().basicGet(queue, true));
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void receiverConsumeManuelAck() throws Exception {
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = RabbitFlux.createReceiver();

    for (int $ : IntStream.range(0, 10).toArray()) {
        Flux<AcknowledgableDelivery> flux = receiver.consumeManualAck(queue);

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }//from  ww w . j  a  v a  2 s .com

        CountDownLatch latch = new CountDownLatch(nbMessages * 2);
        AtomicInteger counter = new AtomicInteger();
        Disposable subscription = flux.bufferTimeout(5, Duration.ofSeconds(1)).subscribe(messages -> {
            counter.addAndGet(messages.size());
            messages.forEach(msg -> {
                msg.ack();
                latch.countDown();
            });
        });

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }

        assertTrue(latch.await(1, TimeUnit.SECONDS));
        subscription.dispose();
        assertEquals(nbMessages * 2, counter.get());
    }

    assertNull(connection.createChannel().basicGet(queue, true));
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void receiverConsumeManuelAckOverflowMessagesRequeued() throws Exception {
    // Downstream would request only one message and the hook before emission
    // would nack/requeue messages.
    // Messages are then redelivered, so a nack can fail because
    // the channel is closed (the subscription is cancelled once the 20
    // published messages have been acked (first one) and at least 19 have
    // been nacked. This can lead to some stack trace in the console, but
    // it's normal behavior.
    // This can be an example of trying no to loose messages and requeue
    // messages when the downstream consumers are overloaded
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = RabbitFlux.createReceiver();

    CountDownLatch ackedNackedLatch = new CountDownLatch(2 * nbMessages - 1);

    Flux<AcknowledgableDelivery> flux = receiver.consumeManualAck(queue,
            new ConsumeOptions().overflowStrategy(FluxSink.OverflowStrategy.DROP)
                    .hookBeforeEmitBiFunction((requestedFromDownstream, message) -> {
                        if (requestedFromDownstream == 0) {
                            ((AcknowledgableDelivery) message).nack(true);
                            ackedNackedLatch.countDown();
                            return false;
                        } else {
                            return true;
                        }//from   w ww.  j  ava  2  s  . c o  m
                    }).qos(1));

    for (int $$ : IntStream.range(0, nbMessages).toArray()) {
        channel.basicPublish("", queue, null, "Hello".getBytes());
    }

    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger counter = new AtomicInteger();
    AtomicReference<Subscription> subscriptionReference = new AtomicReference<>();
    flux.subscribe(new BaseSubscriber<AcknowledgableDelivery>() {

        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            subscription.request(1);
            subscriptionReference.set(subscription);
        }

        @Override
        protected void hookOnNext(AcknowledgableDelivery message) {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            counter.addAndGet(1);
            message.ack();
            latch.countDown();
            subscriptionReference.get().request(0);
        }
    });

    for (int $$ : IntStream.range(0, nbMessages).toArray()) {
        channel.basicPublish("", queue, null, "Hello".getBytes());
    }

    assertTrue(latch.await(1, TimeUnit.SECONDS));
    assertTrue(ackedNackedLatch.await(1, TimeUnit.SECONDS));
    subscriptionReference.get().cancel();
    assertEquals(1, counter.get());
    assertTrue(connection.createChannel().queueDeclarePassive(queue).getMessageCount() > 0);
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void receiverConsumeManuelAckOverflowMessagesDropped() throws Exception {
    // downstream would request only one message and the hook before emission
    // would ack other messages.
    // This can be an example of controlling back pressure by dropping
    // messages (because they're non-essential) with RabbitMQ QoS+ack and
    // reactor feedback from downstream.
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = RabbitFlux.createReceiver();

    CountDownLatch ackedDroppedLatch = new CountDownLatch(2 * nbMessages - 1);

    Flux<AcknowledgableDelivery> flux = receiver.consumeManualAck(queue,
            new ConsumeOptions().overflowStrategy(FluxSink.OverflowStrategy.DROP)
                    .hookBeforeEmitBiFunction((requestedFromDownstream, message) -> {
                        if (requestedFromDownstream == 0) {
                            ((AcknowledgableDelivery) message).ack();
                            ackedDroppedLatch.countDown();
                        }/*  w  w  w . j  a v  a2 s .c  o  m*/
                        // we can emit, the message will be dropped by the overflow strategy
                        return true;
                    }).qos(1));

    for (int $$ : IntStream.range(0, nbMessages).toArray()) {
        channel.basicPublish("", queue, null, "Hello".getBytes());
    }

    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger counter = new AtomicInteger();
    AtomicReference<Subscription> subscriptionReference = new AtomicReference<>();
    flux.subscribe(new BaseSubscriber<AcknowledgableDelivery>() {

        @Override
        protected void hookOnSubscribe(Subscription subscription) {
            subscription.request(1);
            subscriptionReference.set(subscription);
        }

        @Override
        protected void hookOnNext(AcknowledgableDelivery message) {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            counter.addAndGet(1);
            message.ack();
            latch.countDown();
            subscriptionReference.get().request(0);
        }
    });

    for (int $$ : IntStream.range(0, nbMessages).toArray()) {
        channel.basicPublish("", queue, null, "Hello".getBytes());
    }

    assertTrue(ackedDroppedLatch.await(1, TimeUnit.SECONDS));
    assertTrue(latch.await(1, TimeUnit.SECONDS));
    subscriptionReference.get().cancel();
    assertEquals(1, counter.get());
    assertNull(connection.createChannel().basicGet(queue, true));
}

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 .j  a va  2s  . c  om*/
    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// ww w  . ja  va  2  s.c  om
    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

@ParameterizedTest
@MethodSource("noAckAndManualAckFluxArguments")
public void receiverFluxDisposedOnConnectionClose(
        BiFunction<Receiver, String, Flux<? extends Delivery>> fluxFactory) throws Exception {
    Channel channel = connection.createChannel();
    int nbMessages = 10;
    Mono<Connection> connectionMono = Mono.fromCallable(() -> {
        ConnectionFactory cf = new ConnectionFactory();
        cf.useNio();/*from w  w  w .j a  v a 2 s.co  m*/
        return cf.newConnection();
    }).cache();
    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionMono(connectionMono));

    Flux<? extends Delivery> flux = fluxFactory.apply(receiver, queue);
    for (int $$ : IntStream.range(0, nbMessages).toArray()) {
        channel.basicPublish("", queue, null, "Hello".getBytes());
    }

    CountDownLatch messageReceivedLatch = new CountDownLatch(nbMessages);
    CountDownLatch completedLatch = new CountDownLatch(1);
    AtomicInteger counter = new AtomicInteger();
    Disposable subscription = flux.subscribe(msg -> {
        counter.incrementAndGet();
        messageReceivedLatch.countDown();
    }, error -> {
    }, () -> completedLatch.countDown());

    assertTrue(messageReceivedLatch.await(1, TimeUnit.SECONDS));
    assertEquals(nbMessages, counter.get());
    assertEquals(1, completedLatch.getCount());
    connectionMono.block().close();
    assertTrue(completedLatch.await(1, TimeUnit.SECONDS));
    subscription.dispose();
}

From source file:reactor.rabbitmq.ReactorRabbitMqTests.java

License:Open Source License

@Test
public void receiverConsumeNoAck() throws Exception {
    Channel channel = connection.createChannel();
    int nbMessages = 10;

    receiver = ReactorRabbitMq.createReceiver();

    for (int $ : IntStream.range(0, 1).toArray()) {
        Flux<Delivery> flux = receiver.consumeNoAck(queue,
                new ReceiverOptions().overflowStrategy(FluxSink.OverflowStrategy.BUFFER));
        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }//from w w  w. j  av  a 2  s  .co  m

        CountDownLatch latch = new CountDownLatch(nbMessages * 2);
        AtomicInteger counter = new AtomicInteger();
        Disposable subscription = flux.subscribe(msg -> {
            counter.incrementAndGet();
            latch.countDown();
        });

        for (int $$ : IntStream.range(0, nbMessages).toArray()) {
            channel.basicPublish("", queue, null, "Hello".getBytes());
        }

        assertTrue(latch.await(1, TimeUnit.SECONDS));
        subscription.dispose();
        assertEquals(nbMessages * 2, counter.get());
    }
    assertNull(connection.createChannel().basicGet(queue, true));
}