Search in sources :

Example 1 with Consumer

use of com.rabbitmq.stream.Consumer in project rabbitmq-stream-java-client by rabbitmq.

the class StreamEnvironmentTest method environmentPublishersConsumersShouldCloseSuccessfullyWhenBrokerIsDown.

@Test
@TestUtils.DisabledIfRabbitMqCtlNotSet
void environmentPublishersConsumersShouldCloseSuccessfullyWhenBrokerIsDown() throws Exception {
    Environment environment = environmentBuilder.recoveryBackOffDelayPolicy(BackOffDelayPolicy.fixed(Duration.ofSeconds(10))).build();
    CountDownLatch consumeLatch = new CountDownLatch(2);
    Consumer consumer = environment.consumerBuilder().stream(stream).messageHandler((context, message) -> consumeLatch.countDown()).build();
    // will be closed by the environment
    environment.consumerBuilder().stream(stream).messageHandler((context, message) -> consumeLatch.countDown()).build();
    Producer producer = environment.producerBuilder().stream(stream).build();
    // will be closed by the environment
    environment.producerBuilder().stream(stream).build();
    producer.send(producer.messageBuilder().addData("".getBytes(StandardCharsets.UTF_8)).build(), confirmationStatus -> {
    });
    latchAssert(consumeLatch).completes();
    try {
        Host.rabbitmqctl("stop_app");
        producer.close();
        consumer.close();
        environment.close();
    } finally {
        Host.rabbitmqctl("start_app");
    }
    waitAtMost(30, () -> {
        Client client = cf.get();
        Map<String, StreamMetadata> metadata = client.metadata(stream);
        return metadata.containsKey(stream) && metadata.get(stream).isResponseOk();
    });
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SNIHostName(javax.net.ssl.SNIHostName) Message(com.rabbitmq.stream.Message) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Random(java.util.Random) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) AuthenticationFailureException(com.rabbitmq.stream.AuthenticationFailureException) AfterAll(org.junit.jupiter.api.AfterAll) StreamException(com.rabbitmq.stream.StreamException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) ConsumerBuilder(com.rabbitmq.stream.ConsumerBuilder) Duration(java.time.Duration) Map(java.util.Map) Host(com.rabbitmq.stream.Host) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) Collection(java.util.Collection) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) BackOffDelayPolicy(com.rabbitmq.stream.BackOffDelayPolicy) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) StreamCreator(com.rabbitmq.stream.StreamCreator) SslHandler(io.netty.handler.ssl.SslHandler) ProducerBuilder(com.rabbitmq.stream.ProducerBuilder) Constants(com.rabbitmq.stream.Constants) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IntStream(java.util.stream.IntStream) SSLParameters(javax.net.ssl.SSLParameters) StreamMetadata(com.rabbitmq.stream.impl.Client.StreamMetadata) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) Address(com.rabbitmq.stream.Address) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) EnvironmentInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.EnvironmentInfo) ConnectException(java.net.ConnectException) ChannelCustomizer(com.rabbitmq.stream.ChannelCustomizer) ValueSource(org.junit.jupiter.params.provider.ValueSource) EventLoopGroup(io.netty.channel.EventLoopGroup) Environment(com.rabbitmq.stream.Environment) Consumer(com.rabbitmq.stream.Consumer) Producer(com.rabbitmq.stream.Producer) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) DisabledIfTlsNotEnabled(com.rabbitmq.stream.impl.TestUtils.DisabledIfTlsNotEnabled) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) TestUtils.localhostTls(com.rabbitmq.stream.impl.TestUtils.localhostTls) StreamMetadata(com.rabbitmq.stream.impl.Client.StreamMetadata) Consumer(com.rabbitmq.stream.Consumer) Producer(com.rabbitmq.stream.Producer) Environment(com.rabbitmq.stream.Environment) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 2 with Consumer

use of com.rabbitmq.stream.Consumer in project rabbitmq-stream-java-client by rabbitmq.

the class StreamEnvironmentTest method producersAndConsumersShouldBeClosedWhenEnvironmentIsClosed.

@ParameterizedTest
@ValueSource(booleans = { false, true })
void producersAndConsumersShouldBeClosedWhenEnvironmentIsClosed(boolean lazyInit) {
    Environment environment = environmentBuilder.lazyInitialization(lazyInit).build();
    Collection<Producer> producers = IntStream.range(0, 2).mapToObj(i -> environment.producerBuilder().stream(stream).build()).collect(Collectors.toList());
    Collection<Consumer> consumers = IntStream.range(0, 2).mapToObj(i -> environment.consumerBuilder().stream(stream).name(UUID.randomUUID().toString()).messageHandler((offset, message) -> {
    }).build()).collect(Collectors.toList());
    producers.forEach(producer -> assertThat(((StreamProducer) producer).isOpen()).isTrue());
    consumers.forEach(consumer -> assertThat(((StreamConsumer) consumer).isOpen()).isTrue());
    EnvironmentInfo environmentInfo = MonitoringTestUtils.extract(environment);
    assertThat(environmentInfo.getLocator()).isNotNull();
    assertThat(environmentInfo.getProducers()).hasSize(1).element(0).extracting(pool -> pool.getClients()).asList().hasSize(1);
    assertThat(environmentInfo.getProducers().get(0).getClients().get(0).getProducerCount()).isEqualTo(2);
    assertThat(environmentInfo.getProducers().get(0).getClients().get(0).getTrackingConsumerCount()).isEqualTo(2);
    assertThat(environmentInfo.getConsumers()).hasSize(1).element(0).extracting(pool -> pool.getClients()).asList().hasSize(1);
    assertThat(environmentInfo.getConsumers().get(0).getClients().get(0).getConsumerCount()).isEqualTo(2);
    environment.close();
    producers.forEach(producer -> assertThat(((StreamProducer) producer).isOpen()).isFalse());
    consumers.forEach(consumer -> assertThat(((StreamConsumer) consumer).isOpen()).isFalse());
    environmentInfo = MonitoringTestUtils.extract(environment);
    assertThat(environmentInfo.getLocator()).isNull();
    assertThat(environmentInfo.getProducers()).isEmpty();
    assertThat(environmentInfo.getConsumers()).isEmpty();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) SNIHostName(javax.net.ssl.SNIHostName) Message(com.rabbitmq.stream.Message) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Random(java.util.Random) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) AuthenticationFailureException(com.rabbitmq.stream.AuthenticationFailureException) AfterAll(org.junit.jupiter.api.AfterAll) StreamException(com.rabbitmq.stream.StreamException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) ConsumerBuilder(com.rabbitmq.stream.ConsumerBuilder) Duration(java.time.Duration) Map(java.util.Map) Host(com.rabbitmq.stream.Host) TestUtils.waitAtMost(com.rabbitmq.stream.impl.TestUtils.waitAtMost) Collection(java.util.Collection) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) BackOffDelayPolicy(com.rabbitmq.stream.BackOffDelayPolicy) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) StreamCreator(com.rabbitmq.stream.StreamCreator) SslHandler(io.netty.handler.ssl.SslHandler) ProducerBuilder(com.rabbitmq.stream.ProducerBuilder) Constants(com.rabbitmq.stream.Constants) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IntStream(java.util.stream.IntStream) SSLParameters(javax.net.ssl.SSLParameters) StreamMetadata(com.rabbitmq.stream.impl.Client.StreamMetadata) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) Address(com.rabbitmq.stream.Address) ConfirmationHandler(com.rabbitmq.stream.ConfirmationHandler) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) EnvironmentInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.EnvironmentInfo) ConnectException(java.net.ConnectException) ChannelCustomizer(com.rabbitmq.stream.ChannelCustomizer) ValueSource(org.junit.jupiter.params.provider.ValueSource) EventLoopGroup(io.netty.channel.EventLoopGroup) Environment(com.rabbitmq.stream.Environment) Consumer(com.rabbitmq.stream.Consumer) Producer(com.rabbitmq.stream.Producer) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) DisabledIfTlsNotEnabled(com.rabbitmq.stream.impl.TestUtils.DisabledIfTlsNotEnabled) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) TestUtils.localhostTls(com.rabbitmq.stream.impl.TestUtils.localhostTls) Producer(com.rabbitmq.stream.Producer) Consumer(com.rabbitmq.stream.Consumer) EnvironmentInfo(com.rabbitmq.stream.impl.MonitoringTestUtils.EnvironmentInfo) Environment(com.rabbitmq.stream.Environment) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with Consumer

use of com.rabbitmq.stream.Consumer in project rabbitmq-stream-java-client by rabbitmq.

the class StreamEnvironmentTest method locatorShouldReconnectIfConnectionIsLost.

@Test
@TestUtils.DisabledIfRabbitMqCtlNotSet
void locatorShouldReconnectIfConnectionIsLost(TestInfo info) throws Exception {
    try (Environment environment = environmentBuilder.recoveryBackOffDelayPolicy(BackOffDelayPolicy.fixed(Duration.ofSeconds(1))).build()) {
        String s = streamName(info);
        environment.streamCreator().stream(s).create();
        environment.deleteStream(s);
        Host.killConnection("rabbitmq-stream-locator-0");
        environment.streamCreator().stream(s).create();
        try {
            Producer producer = environment.producerBuilder().stream(s).build();
            Consumer consumer = environment.consumerBuilder().stream(s).build();
            producer.close();
            consumer.close();
        } finally {
            environment.deleteStream(s);
        }
    }
}
Also used : Producer(com.rabbitmq.stream.Producer) Consumer(com.rabbitmq.stream.Consumer) Environment(com.rabbitmq.stream.Environment) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with Consumer

use of com.rabbitmq.stream.Consumer in project rabbitmq-stream-java-client by rabbitmq.

the class SuperStreamConsumerTest method consumeAllMessagesFromAllPartitions.

@Test
void consumeAllMessagesFromAllPartitions() throws Exception {
    declareSuperStreamTopology(connection, superStream, partitionCount);
    Client client = cf.get();
    List<String> partitions = client.partitions(superStream);
    int messageCount = 10000 * partitionCount;
    publishToPartitions(cf, partitions, messageCount);
    ConcurrentMap<String, AtomicInteger> messagesReceived = new ConcurrentHashMap<>(partitionCount);
    partitions.forEach(p -> messagesReceived.put(p, new AtomicInteger(0)));
    CountDownLatch consumeLatch = new CountDownLatch(messageCount);
    Consumer consumer = environment.consumerBuilder().superStream(superStream).offset(OffsetSpecification.first()).messageHandler((context, message) -> {
        String partition = new String(message.getBodyAsBinary());
        messagesReceived.get(partition).incrementAndGet();
        consumeLatch.countDown();
    }).build();
    latchAssert(consumeLatch).completes();
    assertThat(messagesReceived).hasSize(partitionCount);
    partitions.forEach(p -> {
        assertThat(messagesReceived).containsKey(p);
        assertThat(messagesReceived.get(p).get()).isEqualTo(messageCount / partitionCount);
    });
    consumer.close();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) Connection(com.rabbitmq.client.Connection) TestUtils.b(com.rabbitmq.stream.impl.TestUtils.b) ClientParameters(com.rabbitmq.stream.impl.Client.ClientParameters) ConcurrentMap(java.util.concurrent.ConcurrentMap) TestUtils.deleteSuperStreamTopology(com.rabbitmq.stream.impl.TestUtils.deleteSuperStreamTopology) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestUtils.declareSuperStreamTopology(com.rabbitmq.stream.impl.TestUtils.declareSuperStreamTopology) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EventLoopGroup(io.netty.channel.EventLoopGroup) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Environment(com.rabbitmq.stream.Environment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Consumer(com.rabbitmq.stream.Consumer) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) Collections(java.util.Collections) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) Consumer(com.rabbitmq.stream.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 5 with Consumer

use of com.rabbitmq.stream.Consumer in project rabbitmq-stream-java-client by rabbitmq.

the class SuperStreamConsumerTest method autoOffsetTrackingShouldStoreOnAllPartitions.

@Test
void autoOffsetTrackingShouldStoreOnAllPartitions() throws Exception {
    declareSuperStreamTopology(connection, superStream, partitionCount);
    Client client = cf.get();
    List<String> partitions = client.partitions(superStream);
    int messageCount = 10000 * partitionCount;
    publishToPartitions(cf, partitions, messageCount);
    ConcurrentMap<String, AtomicInteger> messagesReceived = new ConcurrentHashMap<>(partitionCount);
    ConcurrentMap<String, Long> lastOffsets = new ConcurrentHashMap<>(partitionCount);
    partitions.forEach(p -> {
        messagesReceived.put(p, new AtomicInteger(0));
    });
    CountDownLatch consumeLatch = new CountDownLatch(messageCount);
    String consumerName = "my-app";
    AtomicInteger totalCount = new AtomicInteger();
    Consumer consumer = environment.consumerBuilder().superStream(superStream).offset(OffsetSpecification.first()).name(consumerName).autoTrackingStrategy().messageCountBeforeStorage(messageCount / partitionCount / 50).builder().messageHandler((context, message) -> {
        String partition = new String(message.getBodyAsBinary());
        messagesReceived.get(partition).incrementAndGet();
        lastOffsets.put(partition, context.offset());
        totalCount.incrementAndGet();
        if (totalCount.get() % 50 == 0) {
            context.storeOffset();
        }
        consumeLatch.countDown();
    }).build();
    latchAssert(consumeLatch).completes();
    assertThat(messagesReceived).hasSize(partitionCount);
    partitions.forEach(p -> {
        assertThat(messagesReceived).containsKey(p);
        assertThat(messagesReceived.get(p).get()).isEqualTo(messageCount / partitionCount);
    });
    // checking stored offsets are big enough
    // offset near the end (the message count per partition minus a few messages)
    long almostLastOffset = messageCount / partitionCount - messageCount / (partitionCount * 10);
    partitions.forEach(p -> assertThat(client.queryOffset(consumerName, p).getOffset()).isGreaterThan(almostLastOffset));
    consumer.close();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TestUtils.latchAssert(com.rabbitmq.stream.impl.TestUtils.latchAssert) Connection(com.rabbitmq.client.Connection) TestUtils.b(com.rabbitmq.stream.impl.TestUtils.b) ClientParameters(com.rabbitmq.stream.impl.Client.ClientParameters) ConcurrentMap(java.util.concurrent.ConcurrentMap) TestUtils.deleteSuperStreamTopology(com.rabbitmq.stream.impl.TestUtils.deleteSuperStreamTopology) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestUtils.declareSuperStreamTopology(com.rabbitmq.stream.impl.TestUtils.declareSuperStreamTopology) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EventLoopGroup(io.netty.channel.EventLoopGroup) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Environment(com.rabbitmq.stream.Environment) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Consumer(com.rabbitmq.stream.Consumer) EnvironmentBuilder(com.rabbitmq.stream.EnvironmentBuilder) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) Collections(java.util.Collections) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) TestUtils.localhost(com.rabbitmq.stream.impl.TestUtils.localhost) CountDownLatch(java.util.concurrent.CountDownLatch) Consumer(com.rabbitmq.stream.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.jupiter.api.Test)

Aggregations

Consumer (com.rabbitmq.stream.Consumer)25 Environment (com.rabbitmq.stream.Environment)24 OffsetSpecification (com.rabbitmq.stream.OffsetSpecification)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 Test (org.junit.jupiter.api.Test)22 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)21 EnvironmentBuilder (com.rabbitmq.stream.EnvironmentBuilder)20 Producer (com.rabbitmq.stream.Producer)19 TestUtils.latchAssert (com.rabbitmq.stream.impl.TestUtils.latchAssert)19 TestUtils.localhost (com.rabbitmq.stream.impl.TestUtils.localhost)19 EventLoopGroup (io.netty.channel.EventLoopGroup)19 BeforeEach (org.junit.jupiter.api.BeforeEach)19 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)19 Collections (java.util.Collections)18 List (java.util.List)18 ConfirmationHandler (com.rabbitmq.stream.ConfirmationHandler)17 Duration (java.time.Duration)17 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)16 TestInfo (org.junit.jupiter.api.TestInfo)16 AfterEach (org.junit.jupiter.api.AfterEach)15