Search in sources :

Example 21 with MessageRoutingMode

use of org.apache.pulsar.client.api.MessageRoutingMode in project incubator-pulsar by apache.

the class AdminApi2Test method testPartitionedStatsAggregationByProducerName.

@Test(dataProvider = "topicType")
public void testPartitionedStatsAggregationByProducerName(String topicType) throws Exception {
    conf.setAggregatePublisherStatsByProducerName(true);
    final String topic = topicType + "://prop-xyz/ns1/test-partitioned-stats-aggregation-by-producer-name";
    admin.topics().createPartitionedTopic(topic, 10);
    @Cleanup Producer<byte[]> producer1 = pulsarClient.newProducer().topic(topic).enableLazyStartPartitionedProducers(true).enableBatching(false).messageRoutingMode(MessageRoutingMode.CustomPartition).messageRouter(new MessageRouter() {

        @Override
        public int choosePartition(Message<?> msg, TopicMetadata metadata) {
            return msg.hasKey() ? Integer.parseInt(msg.getKey()) : 0;
        }
    }).accessMode(ProducerAccessMode.Shared).create();
    @Cleanup Producer<byte[]> producer2 = pulsarClient.newProducer().topic(topic).enableLazyStartPartitionedProducers(true).enableBatching(false).messageRoutingMode(MessageRoutingMode.CustomPartition).messageRouter(new MessageRouter() {

        @Override
        public int choosePartition(Message<?> msg, TopicMetadata metadata) {
            return msg.hasKey() ? Integer.parseInt(msg.getKey()) : 5;
        }
    }).accessMode(ProducerAccessMode.Shared).create();
    for (int i = 0; i < 10; i++) {
        producer1.newMessage().key(String.valueOf(i % 5)).value(("message".getBytes(StandardCharsets.UTF_8))).send();
        producer2.newMessage().key(String.valueOf(i % 5 + 5)).value(("message".getBytes(StandardCharsets.UTF_8))).send();
    }
    PartitionedTopicStats topicStats = admin.topics().getPartitionedStats(topic, true);
    assertEquals(topicStats.getPartitions().size(), 10);
    assertEquals(topicStats.getPartitions().values().stream().mapToInt(e -> e.getPublishers().size()).sum(), 10);
    assertEquals(topicStats.getPartitions().values().stream().map(e -> e.getPublishers().get(0).getProducerName()).distinct().count(), 2);
    assertEquals(topicStats.getPublishers().size(), 2);
    topicStats.getPublishers().forEach(p -> assertTrue(p.isSupportsPartialProducer()));
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) Topic(org.apache.pulsar.broker.service.Topic) URL(java.net.URL) Producer(org.apache.pulsar.client.api.Producer) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) PreconditionFailedException(org.apache.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) Assert.assertFalse(org.testng.Assert.assertFalse) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) BrokerNamespaceIsolationDataImpl(org.apache.pulsar.common.policies.data.BrokerNamespaceIsolationDataImpl) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) PersistencePolicies(org.apache.pulsar.common.policies.data.PersistencePolicies) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) Assert.assertNotNull(org.testng.Assert.assertNotNull) UUID(java.util.UUID) Sets(com.google.common.collect.Sets) StandardCharsets(java.nio.charset.StandardCharsets) TopicMetadata(org.apache.pulsar.client.api.TopicMetadata) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) BacklogQuotaImpl(org.apache.pulsar.common.policies.data.impl.BacklogQuotaImpl) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) QueryParam(org.apache.pulsar.client.admin.Topics.QueryParam) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription) Optional(java.util.Optional) PersistentTopicInternalStats(org.apache.pulsar.common.policies.data.PersistentTopicInternalStats) NonPersistentTopicStats(org.apache.pulsar.common.policies.data.NonPersistentTopicStats) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) Awaitility(org.awaitility.Awaitility) MockedPulsarService(org.apache.pulsar.broker.admin.AdminApiTest.MockedPulsarService) SimpleLoadManagerImpl(org.apache.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl) TopicName(org.apache.pulsar.common.naming.TopicName) Assert.assertNull(org.testng.Assert.assertNull) DataProvider(org.testng.annotations.DataProvider) TopicStats(org.apache.pulsar.common.policies.data.TopicStats) Assert.assertEquals(org.testng.Assert.assertEquals) ModularLoadManagerImpl(org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl) BacklogQuota(org.apache.pulsar.common.policies.data.BacklogQuota) HashMap(java.util.HashMap) PulsarAdmin(org.apache.pulsar.client.admin.PulsarAdmin) Message(org.apache.pulsar.client.api.Message) Mockito.spy(org.mockito.Mockito.spy) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MessageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode) Lists(com.google.common.collect.Lists) AutoTopicCreationOverride(org.apache.pulsar.common.policies.data.AutoTopicCreationOverride) Assert(org.testng.Assert) BundlesData(org.apache.pulsar.common.policies.data.BundlesData) PulsarClient(org.apache.pulsar.client.api.PulsarClient) TopicDomain(org.apache.pulsar.common.naming.TopicDomain) Status(javax.ws.rs.core.Response.Status) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) NotAcceptableException(javax.ws.rs.NotAcceptableException) BrokerNamespaceIsolationData(org.apache.pulsar.common.policies.data.BrokerNamespaceIsolationData) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) AutoFailoverPolicyType(org.apache.pulsar.common.policies.data.AutoFailoverPolicyType) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) MessageRouter(org.apache.pulsar.client.api.MessageRouter) Assert.fail(org.testng.Assert.fail) FailureDomain(org.apache.pulsar.common.policies.data.FailureDomain) Mockito.times(org.mockito.Mockito.times) Field(java.lang.reflect.Field) PulsarService(org.apache.pulsar.broker.PulsarService) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Maps(com.google.common.collect.Maps) Mockito.verify(org.mockito.Mockito.verify) Schema(org.apache.pulsar.client.api.Schema) TimeUnit(java.util.concurrent.TimeUnit) PartitionedTopicStats(org.apache.pulsar.common.policies.data.PartitionedTopicStats) MessageId(org.apache.pulsar.client.api.MessageId) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ProxyProtocol(org.apache.pulsar.client.api.ProxyProtocol) ProducerAccessMode(org.apache.pulsar.client.api.ProducerAccessMode) Assert.assertTrue(org.testng.Assert.assertTrue) BrokerTestUtil(org.apache.pulsar.broker.BrokerTestUtil) ConsumerStats(org.apache.pulsar.common.policies.data.ConsumerStats) Collections(java.util.Collections) AutoFailoverPolicyData(org.apache.pulsar.common.policies.data.AutoFailoverPolicyData) NamespaceIsolationData(org.apache.pulsar.common.policies.data.NamespaceIsolationData) MessageRouter(org.apache.pulsar.client.api.MessageRouter) PartitionedTopicStats(org.apache.pulsar.common.policies.data.PartitionedTopicStats) Cleanup(lombok.Cleanup) AutoTopicCreationOverride(org.apache.pulsar.common.policies.data.AutoTopicCreationOverride) TopicMetadata(org.apache.pulsar.client.api.TopicMetadata) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 22 with MessageRoutingMode

use of org.apache.pulsar.client.api.MessageRoutingMode in project incubator-pulsar by apache.

the class RawReaderTest method testBatchingRebatch.

@Test
public void testBatchingRebatch() throws Exception {
    String topic = "persistent://my-property/my-ns/my-raw-topic";
    try (Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).maxPendingMessages(3).enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS).messageRoutingMode(MessageRoutingMode.SinglePartition).create()) {
        producer.newMessage().key("key1").value("my-content-1".getBytes()).sendAsync();
        producer.newMessage().key("key2").value("my-content-2".getBytes()).sendAsync();
        producer.newMessage().key("key3").value("my-content-3".getBytes()).send();
    }
    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    try (RawMessage m1 = reader.readNextAsync().get()) {
        RawMessage m2 = RawBatchConverter.rebatchMessage(m1, (key, id) -> key.equals("key2")).get();
        List<ImmutableTriple<MessageId, String, Integer>> idsAndKeys = RawBatchConverter.extractIdsAndKeysAndSize(m2);
        Assert.assertEquals(idsAndKeys.size(), 1);
        Assert.assertEquals(idsAndKeys.get(0).getMiddle(), "key2");
        m2.close();
        Assert.assertEquals(m1.getHeadersAndPayload().refCnt(), 1);
    } finally {
        reader.closeAsync().get();
    }
}
Also used : RawMessage(org.apache.pulsar.client.api.RawMessage) Producer(org.apache.pulsar.client.api.Producer) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) RawReader(org.apache.pulsar.client.api.RawReader) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) ArrayList(java.util.ArrayList) Commands(org.apache.pulsar.common.protocol.Commands) HashSet(java.util.HashSet) MessageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode) Future(java.util.concurrent.Future) ByteBuf(io.netty.buffer.ByteBuf) Assert(org.testng.Assert) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) CancellationException(java.util.concurrent.CancellationException) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) MessageId(org.apache.pulsar.client.api.MessageId) MessageMetadata(org.apache.pulsar.common.api.proto.MessageMetadata) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) Awaitility(org.awaitility.Awaitility) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) RawReader(org.apache.pulsar.client.api.RawReader) RawMessage(org.apache.pulsar.client.api.RawMessage) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 23 with MessageRoutingMode

use of org.apache.pulsar.client.api.MessageRoutingMode in project pulsar by yahoo.

the class TopicsConsumerImplTest method testAsyncConsumer.

@Test(timeOut = testTimeout)
public void testAsyncConsumer() throws Exception {
    String key = "TopicsConsumerAsyncTest";
    final String subscriptionName = "my-ex-subscription-" + key;
    final String messagePredicate = "my-message-" + key + "-";
    final int totalMessages = 30;
    final String topicName1 = "persistent://prop/use/ns-abc/topic-1-" + key;
    final String topicName2 = "persistent://prop/use/ns-abc/topic-2-" + key;
    final String topicName3 = "persistent://prop/use/ns-abc/topic-3-" + key;
    List<String> topicNames = Lists.newArrayList(topicName1, topicName2, topicName3);
    TenantInfoImpl tenantInfo = createDefaultTenantInfo();
    admin.tenants().createTenant("prop", tenantInfo);
    admin.topics().createPartitionedTopic(topicName2, 2);
    admin.topics().createPartitionedTopic(topicName3, 3);
    // 1. producer connect
    Producer<byte[]> producer1 = pulsarClient.newProducer().topic(topicName1).enableBatching(false).messageRoutingMode(MessageRoutingMode.SinglePartition).create();
    Producer<byte[]> producer2 = pulsarClient.newProducer().topic(topicName2).enableBatching(false).messageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode.RoundRobinPartition).create();
    Producer<byte[]> producer3 = pulsarClient.newProducer().topic(topicName3).enableBatching(false).messageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode.RoundRobinPartition).create();
    // 2. Create consumer
    Consumer<byte[]> consumer = pulsarClient.newConsumer().topics(topicNames).subscriptionName(subscriptionName).subscriptionType(SubscriptionType.Shared).ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).receiverQueueSize(4).subscribe();
    assertTrue(consumer instanceof MultiTopicsConsumerImpl);
    // Asynchronously produce messages
    List<Future<MessageId>> futures = Lists.newArrayList();
    for (int i = 0; i < totalMessages / 3; i++) {
        futures.add(producer1.sendAsync((messagePredicate + "producer1-" + i).getBytes()));
        futures.add(producer2.sendAsync((messagePredicate + "producer2-" + i).getBytes()));
        futures.add(producer3.sendAsync((messagePredicate + "producer3-" + i).getBytes()));
    }
    log.info("Waiting for async publish to complete : {}", futures.size());
    for (Future<MessageId> future : futures) {
        future.get();
    }
    log.info("start async consume");
    CountDownLatch latch = new CountDownLatch(totalMessages);
    @Cleanup("shutdownNow") ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(() -> IntStream.range(0, totalMessages).forEach(index -> consumer.receiveAsync().thenAccept(msg -> {
        assertTrue(msg instanceof TopicMessageImpl);
        try {
            consumer.acknowledge(msg);
        } catch (PulsarClientException e1) {
            fail("message acknowledge failed", e1);
        }
        latch.countDown();
        log.info("receive index: {}, latch countDown: {}", index, latch.getCount());
    }).exceptionally(ex -> {
        log.warn("receive index: {}, failed receive message {}", index, ex.getMessage());
        ex.printStackTrace();
        return null;
    })));
    latch.await();
    log.info("success latch wait");
    consumer.unsubscribe();
    consumer.close();
    producer1.close();
    producer2.close();
    producer3.close();
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) Topic(org.apache.pulsar.broker.service.Topic) Producer(org.apache.pulsar.client.api.Producer) LoggerFactory(org.slf4j.LoggerFactory) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) BeforeMethod(org.testng.annotations.BeforeMethod) Assert.assertNotNull(org.testng.Assert.assertNotNull) Sets(com.google.common.collect.Sets) Executors(java.util.concurrent.Executors) TopicMetadata(org.apache.pulsar.client.api.TopicMetadata) Consumer(org.apache.pulsar.client.api.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription) Optional(java.util.Optional) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) Awaitility(org.awaitility.Awaitility) ProducerConsumerBase(org.apache.pulsar.client.api.ProducerConsumerBase) IntStream(java.util.stream.IntStream) TopicStats(org.apache.pulsar.common.policies.data.TopicStats) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Message(org.apache.pulsar.client.api.Message) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) MessageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode) Lists(com.google.common.collect.Lists) Assert(org.testng.Assert) PulsarClient(org.apache.pulsar.client.api.PulsarClient) ExecutorService(java.util.concurrent.ExecutorService) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) MessageRouter(org.apache.pulsar.client.api.MessageRouter) Assert.fail(org.testng.Assert.fail) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Schema(org.apache.pulsar.client.api.Schema) TimeUnit(java.util.concurrent.TimeUnit) PartitionedTopicStats(org.apache.pulsar.common.policies.data.PartitionedTopicStats) MessageId(org.apache.pulsar.client.api.MessageId) Assert.assertTrue(org.testng.Assert.assertTrue) CountDownLatch(java.util.concurrent.CountDownLatch) Cleanup(lombok.Cleanup) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) ExecutorService(java.util.concurrent.ExecutorService) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Future(java.util.concurrent.Future) CompletableFuture(java.util.concurrent.CompletableFuture) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 24 with MessageRoutingMode

use of org.apache.pulsar.client.api.MessageRoutingMode in project pulsar by yahoo.

the class RawReaderTest method testBatchingRebatch.

@Test
public void testBatchingRebatch() throws Exception {
    String topic = "persistent://my-property/my-ns/my-raw-topic";
    try (Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).maxPendingMessages(3).enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS).messageRoutingMode(MessageRoutingMode.SinglePartition).create()) {
        producer.newMessage().key("key1").value("my-content-1".getBytes()).sendAsync();
        producer.newMessage().key("key2").value("my-content-2".getBytes()).sendAsync();
        producer.newMessage().key("key3").value("my-content-3".getBytes()).send();
    }
    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    try (RawMessage m1 = reader.readNextAsync().get()) {
        RawMessage m2 = RawBatchConverter.rebatchMessage(m1, (key, id) -> key.equals("key2")).get();
        List<ImmutableTriple<MessageId, String, Integer>> idsAndKeys = RawBatchConverter.extractIdsAndKeysAndSize(m2);
        Assert.assertEquals(idsAndKeys.size(), 1);
        Assert.assertEquals(idsAndKeys.get(0).getMiddle(), "key2");
        m2.close();
        Assert.assertEquals(m1.getHeadersAndPayload().refCnt(), 1);
    } finally {
        reader.closeAsync().get();
    }
}
Also used : RawMessage(org.apache.pulsar.client.api.RawMessage) Producer(org.apache.pulsar.client.api.Producer) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) RawReader(org.apache.pulsar.client.api.RawReader) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) ArrayList(java.util.ArrayList) Commands(org.apache.pulsar.common.protocol.Commands) HashSet(java.util.HashSet) MessageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode) Future(java.util.concurrent.Future) ByteBuf(io.netty.buffer.ByteBuf) Assert(org.testng.Assert) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) CancellationException(java.util.concurrent.CancellationException) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) MessageId(org.apache.pulsar.client.api.MessageId) MessageMetadata(org.apache.pulsar.common.api.proto.MessageMetadata) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) Awaitility(org.awaitility.Awaitility) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) RawReader(org.apache.pulsar.client.api.RawReader) RawMessage(org.apache.pulsar.client.api.RawMessage) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 25 with MessageRoutingMode

use of org.apache.pulsar.client.api.MessageRoutingMode in project pulsar by yahoo.

the class PersistentTopicE2ETest method testProducerReturnedMessageId.

@Test
public void testProducerReturnedMessageId() throws Exception {
    final String topicName = "persistent://prop/ns-abc/topic-xyz";
    // 1. producer connect
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).enableBatching(false).messageRoutingMode(MessageRoutingMode.SinglePartition).create();
    PersistentTopic topicRef = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName).get();
    assertNotNull(topicRef);
    assertEquals(topicRef.getProducers().size(), 1);
    ManagedLedgerImpl managedLedger = (ManagedLedgerImpl) topicRef.getManagedLedger();
    long ledgerId = managedLedger.getLedgersInfoAsList().get(0).getLedgerId();
    // 2. producer publish messages
    final int SyncMessages = 10;
    for (int i = 0; i < SyncMessages; i++) {
        String message = "my-message-" + i;
        MessageId receivedMessageId = producer.send(message.getBytes());
        assertEquals(receivedMessageId, new MessageIdImpl(ledgerId, i, -1));
    }
    // 3. producer publish messages async
    final int AsyncMessages = 10;
    final CountDownLatch counter = new CountDownLatch(AsyncMessages);
    for (int i = SyncMessages; i < (SyncMessages + AsyncMessages); i++) {
        String content = "my-message-" + i;
        final int index = i;
        producer.sendAsync(content.getBytes()).thenAccept((msgId) -> {
            assertEquals(msgId, new MessageIdImpl(ledgerId, index, -1));
            counter.countDown();
        }).exceptionally((ex) -> {
            return null;
        });
    }
    counter.await();
    // 4. producer disconnect
    producer.close();
}
Also used : Metrics(org.apache.pulsar.common.stats.Metrics) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) LookupService(org.apache.pulsar.client.impl.LookupService) Producer(org.apache.pulsar.client.api.Producer) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) ByteBuffer(java.nio.ByteBuffer) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ToString(lombok.ToString) Assert.assertFalse(org.testng.Assert.assertFalse) SocketChannel(io.netty.channel.socket.SocketChannel) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ConsumerImpl(org.apache.pulsar.client.impl.ConsumerImpl) CompressionType(org.apache.pulsar.client.api.CompressionType) BeforeMethod(org.testng.annotations.BeforeMethod) Assert.assertNotNull(org.testng.Assert.assertNotNull) EqualsAndHashCode(lombok.EqualsAndHashCode) Sets(com.google.common.collect.Sets) Executors(java.util.concurrent.Executors) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) CountDownLatch(java.util.concurrent.CountDownLatch) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription) Optional(java.util.Optional) JSONSchema(org.apache.pulsar.client.impl.schema.JSONSchema) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) Awaitility(org.awaitility.Awaitility) ProducerImpl(org.apache.pulsar.client.impl.ProducerImpl) TopicName(org.apache.pulsar.common.naming.TopicName) Assert.assertNull(org.testng.Assert.assertNull) DataProvider(org.testng.annotations.DataProvider) Assert.assertEquals(org.testng.Assert.assertEquals) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Message(org.apache.pulsar.client.api.Message) SchemaType(org.apache.pulsar.common.schema.SchemaType) ArrayList(java.util.ArrayList) ProducerBuilder(org.apache.pulsar.client.api.ProducerBuilder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) MessageRoutingMode(org.apache.pulsar.client.api.MessageRoutingMode) SubType(org.apache.pulsar.common.api.proto.CommandSubscribe.SubType) Assert(org.testng.Assert) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ProducerBusyException(org.apache.pulsar.client.api.PulsarClientException.ProducerBusyException) SchemaDefinition(org.apache.pulsar.client.api.schema.SchemaDefinition) PulsarClient(org.apache.pulsar.client.api.PulsarClient) PersistentDispatcherMultipleConsumers(org.apache.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) ExecutorService(java.util.concurrent.ExecutorService) SchemaRegistry(org.apache.pulsar.broker.service.schema.SchemaRegistry) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) TypedMessageBuilder(org.apache.pulsar.client.api.TypedMessageBuilder) TypedMessageBuilderImpl(org.apache.pulsar.client.impl.TypedMessageBuilderImpl) DEFAULT_CONSUMER_EPOCH(org.apache.pulsar.common.protocol.Commands.DEFAULT_CONSUMER_EPOCH) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) MessageRedeliveryController(org.apache.pulsar.broker.service.persistent.MessageRedeliveryController) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) Assert.fail(org.testng.Assert.fail) Field(java.lang.reflect.Field) EntryCacheImpl(org.apache.bookkeeper.mledger.impl.EntryCacheImpl) PulsarService(org.apache.pulsar.broker.PulsarService) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Schema(org.apache.pulsar.client.api.Schema) TimeUnit(java.util.concurrent.TimeUnit) MessageId(org.apache.pulsar.client.api.MessageId) CommandConnect(org.apache.pulsar.common.api.proto.CommandConnect) Data(lombok.Data) Assert.assertTrue(org.testng.Assert.assertTrue) SchemaData(org.apache.pulsar.common.protocol.schema.SchemaData) Schemas(org.apache.pulsar.schema.Schemas) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) ToString(lombok.ToString) CountDownLatch(java.util.concurrent.CountDownLatch) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Aggregations

MessageRoutingMode (org.apache.pulsar.client.api.MessageRoutingMode)32 TimeUnit (java.util.concurrent.TimeUnit)24 Test (org.testng.annotations.Test)24 Sets (com.google.common.collect.Sets)21 Producer (org.apache.pulsar.client.api.Producer)21 PulsarClient (org.apache.pulsar.client.api.PulsarClient)21 Awaitility (org.awaitility.Awaitility)21 Assert (org.testng.Assert)21 Assert.assertEquals (org.testng.Assert.assertEquals)21 Assert.assertTrue (org.testng.Assert.assertTrue)21 BeforeMethod (org.testng.annotations.BeforeMethod)21 ArrayList (java.util.ArrayList)18 List (java.util.List)18 Map (java.util.Map)18 Cleanup (lombok.Cleanup)18 Consumer (org.apache.pulsar.client.api.Consumer)18 HashMap (java.util.HashMap)15 PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)15 MessageId (org.apache.pulsar.client.api.MessageId)15 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)15