Search in sources :

Example 21 with Message

use of com.yahoo.pulsar.client.api.Message in project pulsar by yahoo.

the class PersistentTopicE2ETest method testConcurrentConsumerThreads.

// some race conditions needs to be handled
// disabling the test for now to not block commit jobs
@Test(enabled = false)
public void testConcurrentConsumerThreads() throws Exception {
    // test concurrent consumer threads on same consumerId
    final String topicName = "persistent://prop/use/ns-abc/topic3";
    final String subName = "sub3";
    final int recvQueueSize = 100;
    final int numConsumersThreads = 10;
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Exclusive);
    conf.setReceiverQueueSize(recvQueueSize);
    ExecutorService executor = Executors.newCachedThreadPool();
    final CyclicBarrier barrier = new CyclicBarrier(numConsumersThreads + 1);
    for (int i = 0; i < numConsumersThreads; i++) {
        executor.submit(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                barrier.await();
                Consumer consumer = pulsarClient.subscribe(topicName, subName, conf);
                for (int i = 0; i < recvQueueSize / numConsumersThreads; i++) {
                    Message msg = consumer.receive();
                    consumer.acknowledge(msg);
                }
                return null;
            }
        });
    }
    Producer producer = pulsarClient.createProducer(topicName);
    for (int i = 0; i < recvQueueSize * numConsumersThreads; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    barrier.await();
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
    PersistentTopic topicRef = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    PersistentSubscription subRef = topicRef.getPersistentSubscription(subName);
    // 1. cumulatively all threads drain the backlog
    assertEquals(subRef.getNumberOfEntriesInBacklog(), 0);
    // 2. flow control works the same as single consumer single thread
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
    assertEquals(getAvailablePermits(subRef), recvQueueSize);
}
Also used : Message(com.yahoo.pulsar.client.api.Message) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) CyclicBarrier(java.util.concurrent.CyclicBarrier) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) Test(org.testng.annotations.Test)

Example 22 with Message

use of com.yahoo.pulsar.client.api.Message in project pulsar by yahoo.

the class PersistentTopicE2ETest method testPayloadCorruptionDetection.

@Test
public void testPayloadCorruptionDetection() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/topic1";
    // 1. producer connect
    Producer producer = pulsarClient.createProducer(topicName);
    Consumer consumer = pulsarClient.subscribe(topicName, "my-sub");
    Message msg1 = MessageBuilder.create().setContent("message-1".getBytes()).build();
    CompletableFuture<MessageId> future1 = producer.sendAsync(msg1);
    // Stop the broker, and publishes messages. Messages are accumulated in the producer queue and they're checksums
    // would have already been computed. If we change the message content at that point, it should result in a
    // checksum validation error
    stopBroker();
    Message msg2 = MessageBuilder.create().setContent("message-2".getBytes()).build();
    CompletableFuture<MessageId> future2 = producer.sendAsync(msg2);
    // Taint msg2
    // new content would be 'message-3'
    msg2.getData()[msg2.getData().length - 1] = '3';
    // Restart the broker to have the messages published
    startBroker();
    future1.get();
    try {
        future2.get();
        fail("since we corrupted the message, it should be rejected by the broker");
    } catch (Exception e) {
    // ok
    }
    // We should only receive msg1
    Message msg = consumer.receive(1, TimeUnit.SECONDS);
    assertEquals(new String(msg.getData()), "message-1");
    while ((msg = consumer.receive(1, TimeUnit.SECONDS)) != null) {
        assertEquals(new String(msg.getData()), "message-1");
    }
}
Also used : Producer(com.yahoo.pulsar.client.api.Producer) Consumer(com.yahoo.pulsar.client.api.Consumer) Message(com.yahoo.pulsar.client.api.Message) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) MessageId(com.yahoo.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 23 with Message

use of com.yahoo.pulsar.client.api.Message in project pulsar by yahoo.

the class PersistentTopicE2ETest method testMessageRedelivery.

/**
     * Verify: Broker should not replay already acknowledged messages again and should clear them from messageReplay bucket
     *
     * 1. produce messages
     * 2. consume messages and ack all except 1 msg
     * 3. Verification: should replay only 1 unacked message
     */
@Test()
public void testMessageRedelivery() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/topic2";
    final String subName = "sub2";
    Message msg;
    int totalMessages = 10;
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Shared);
    Consumer consumer = pulsarClient.subscribe(topicName, subName, conf);
    Producer producer = pulsarClient.createProducer(topicName);
    // (1) Produce messages
    for (int i = 0; i < totalMessages; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    //(2) Consume and ack messages except first message
    Message unAckedMsg = null;
    for (int i = 0; i < totalMessages; i++) {
        msg = consumer.receive();
        if (i == 0) {
            unAckedMsg = msg;
        } else {
            consumer.acknowledge(msg);
        }
    }
    consumer.redeliverUnacknowledgedMessages();
    // Verify: msg [L:0] must be redelivered
    try {
        msg = consumer.receive(1, TimeUnit.SECONDS);
        assertEquals(new String(msg.getData()), new String(unAckedMsg.getData()));
    } catch (Exception e) {
        fail("msg should be redelivered ", e);
    }
    // Verify no other messages are redelivered
    msg = consumer.receive(100, TimeUnit.MILLISECONDS);
    assertNull(msg);
    consumer.close();
    producer.close();
}
Also used : Message(com.yahoo.pulsar.client.api.Message) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) Test(org.testng.annotations.Test)

Example 24 with Message

use of com.yahoo.pulsar.client.api.Message in project pulsar by yahoo.

the class PersistentTopicE2ETest method testMessageReplay.

/**
     * Verify: 
     * 1. Broker should not replay already acknowledged messages 
     * 2. Dispatcher should not stuck while dispatching new messages due to previous-replay 
     * of invalid/already-acked messages
     * 
     * @throws Exception
     */
@Test
public void testMessageReplay() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/topic2";
    final String subName = "sub2";
    Message msg;
    int totalMessages = 10;
    int replayIndex = totalMessages / 2;
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Shared);
    conf.setReceiverQueueSize(1);
    Consumer consumer = pulsarClient.subscribe(topicName, subName, conf);
    Producer producer = pulsarClient.createProducer(topicName);
    PersistentTopic topicRef = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    assertNotNull(topicRef);
    PersistentSubscription subRef = topicRef.getPersistentSubscription(subName);
    PersistentDispatcherMultipleConsumers dispatcher = (PersistentDispatcherMultipleConsumers) subRef.getDispatcher();
    Field replayMap = PersistentDispatcherMultipleConsumers.class.getDeclaredField("messagesToReplay");
    replayMap.setAccessible(true);
    TreeSet<PositionImpl> messagesToReplay = Sets.newTreeSet();
    assertNotNull(subRef);
    // (1) Produce messages
    for (int i = 0; i < totalMessages; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    MessageIdImpl firstAckedMsg = null;
    // (2) Consume and ack messages except first message
    for (int i = 0; i < totalMessages; i++) {
        msg = consumer.receive();
        consumer.acknowledge(msg);
        MessageIdImpl msgId = (MessageIdImpl) msg.getMessageId();
        if (i == 0) {
            firstAckedMsg = msgId;
        }
        if (i < replayIndex) {
            // (3) accumulate acked messages for replay
            messagesToReplay.add(new PositionImpl(msgId.getLedgerId(), msgId.getEntryId()));
        }
    }
    // (4) redelivery : should redeliver only unacked messages
    Thread.sleep(1000);
    replayMap.set(dispatcher, messagesToReplay);
    // (a) redelivery with all acked-message should clear messageReply bucket
    dispatcher.redeliverUnacknowledgedMessages(dispatcher.getConsumers().get(0));
    assertEquals(messagesToReplay.size(), 0);
    // (b) fill messageReplyBucket with already acked entry again: and try to publish new msg and read it
    messagesToReplay.add(new PositionImpl(firstAckedMsg.getLedgerId(), firstAckedMsg.getEntryId()));
    replayMap.set(dispatcher, messagesToReplay);
    // send new message
    final String testMsg = "testMsg";
    producer.send(testMsg.getBytes());
    // consumer should be able to receive only new message and not the
    dispatcher.consumerFlow(dispatcher.getConsumers().get(0), 1);
    msg = consumer.receive(1, TimeUnit.SECONDS);
    assertNotNull(msg);
    assertEquals(msg.getData(), testMsg.getBytes());
    consumer.close();
    producer.close();
}
Also used : Message(com.yahoo.pulsar.client.api.Message) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) MessageIdImpl(com.yahoo.pulsar.client.impl.MessageIdImpl) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) Field(java.lang.reflect.Field) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) PersistentDispatcherMultipleConsumers(com.yahoo.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) Test(org.testng.annotations.Test)

Example 25 with Message

use of com.yahoo.pulsar.client.api.Message in project pulsar by yahoo.

the class BatchMessageTest method testSimpleBatchProducerConsumer.

@Test(dataProvider = "codec")
public void testSimpleBatchProducerConsumer(CompressionType compressionType) throws Exception {
    int numMsgs = 500;
    int numMsgsInBatch = numMsgs / 20;
    final String topicName = "persistent://prop/use/ns-abc/testSimpleBatchProducerConsumer";
    final String subscriptionName = "pc-sub-1" + compressionType.toString();
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
    consumer.close();
    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setCompressionType(compressionType);
    producerConf.setBatchingMaxPublishDelay(5000, TimeUnit.MILLISECONDS);
    producerConf.setBatchingMaxMessages(numMsgsInBatch);
    producerConf.setBatchingEnabled(true);
    Producer producer = pulsarClient.createProducer(topicName, producerConf);
    List<CompletableFuture<MessageId>> sendFutureList = Lists.newArrayList();
    for (int i = 0; i < numMsgs; i++) {
        byte[] message = ("msg-" + i).getBytes();
        Message msg = MessageBuilder.create().setContent(message).build();
        sendFutureList.add(producer.sendAsync(msg));
    }
    FutureUtil.waitForAll(sendFutureList).get();
    PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    rolloverPerIntervalStats();
    assertTrue(topic.getProducers().values().iterator().next().getStats().msgRateIn > 0.0);
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), numMsgs / numMsgsInBatch);
    consumer = pulsarClient.subscribe(topicName, subscriptionName);
    Message lastunackedMsg = null;
    for (int i = 0; i < numMsgs; i++) {
        Message msg = consumer.receive(5, TimeUnit.SECONDS);
        assertNotNull(msg);
        if (i % 2 == 0) {
            consumer.acknowledgeCumulative(msg);
        } else {
            lastunackedMsg = msg;
        }
    }
    if (lastunackedMsg != null) {
        consumer.acknowledgeCumulative(lastunackedMsg);
    }
    Thread.sleep(100);
    assertEquals(topic.getPersistentSubscription(subscriptionName).getNumberOfEntriesInBacklog(), 0);
    consumer.close();
    producer.close();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) Message(com.yahoo.pulsar.client.api.Message) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) Test(org.testng.annotations.Test)

Aggregations

Message (com.yahoo.pulsar.client.api.Message)90 Test (org.testng.annotations.Test)66 Consumer (com.yahoo.pulsar.client.api.Consumer)61 Producer (com.yahoo.pulsar.client.api.Producer)57 ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)47 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)31 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)25 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)22 CompletableFuture (java.util.concurrent.CompletableFuture)17 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)10 PulsarAdminException (com.yahoo.pulsar.client.admin.PulsarAdminException)9 MessageId (com.yahoo.pulsar.client.api.MessageId)9 PersistentSubscription (com.yahoo.pulsar.broker.service.persistent.PersistentSubscription)8 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)6 Field (java.lang.reflect.Field)6 HashSet (java.util.HashSet)6 MockedPulsarServiceBaseTest (com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)5 RetentionPolicies (com.yahoo.pulsar.common.policies.data.RetentionPolicies)5 Tuple (backtype.storm.tuple.Tuple)4 ParameterException (com.beust.jcommander.ParameterException)4