Search in sources :

Example 46 with Producer

use of com.yahoo.pulsar.client.api.Producer 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 47 with Producer

use of com.yahoo.pulsar.client.api.Producer 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 48 with Producer

use of com.yahoo.pulsar.client.api.Producer 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 49 with Producer

use of com.yahoo.pulsar.client.api.Producer 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)

Example 50 with Producer

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

the class BrokerServiceTest method testBrokerStatsMetrics.

@Test
public void testBrokerStatsMetrics() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/newTopic";
    final String subName = "newSub";
    BrokerStats brokerStatsClient = admin.brokerStats();
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Exclusive);
    Consumer consumer = pulsarClient.subscribe(topicName, subName, conf);
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
    Producer producer = pulsarClient.createProducer(topicName);
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
    for (int i = 0; i < 10; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
    Message msg = null;
    for (int i = 0; i < 10; i++) {
        msg = consumer.receive();
        consumer.acknowledge(msg);
    }
    consumer.close();
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
    JsonArray metrics = brokerStatsClient.getMetrics();
    assertEquals(metrics.size(), 4, metrics.toString());
    // these metrics seem to be arriving in different order at different times...
    // is the order really relevant here?
    boolean namespaceDimensionFound = false;
    boolean topicLoadTimesDimensionFound = false;
    for (int i = 0; i < metrics.size(); i++) {
        try {
            String data = metrics.get(i).getAsJsonObject().get("dimensions").toString();
            if (!namespaceDimensionFound && data.contains("prop/use/ns-abc")) {
                namespaceDimensionFound = true;
            }
            if (!topicLoadTimesDimensionFound && data.contains("prop/use/ns-abc")) {
                topicLoadTimesDimensionFound = true;
            }
        } catch (Exception e) {
        /* it's possible there's no dimensions */
        }
    }
    assertTrue(namespaceDimensionFound && topicLoadTimesDimensionFound);
    Thread.sleep(ASYNC_EVENT_COMPLETION_WAIT);
}
Also used : JsonArray(com.google.gson.JsonArray) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) Message(com.yahoo.pulsar.client.api.Message) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) BrokerStats(com.yahoo.pulsar.client.admin.BrokerStats) IOException(java.io.IOException) Test(org.testng.annotations.Test)

Aggregations

Producer (com.yahoo.pulsar.client.api.Producer)105 Test (org.testng.annotations.Test)90 Consumer (com.yahoo.pulsar.client.api.Consumer)71 Message (com.yahoo.pulsar.client.api.Message)57 ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)51 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)35 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)32 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)30 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)27 CompletableFuture (java.util.concurrent.CompletableFuture)20 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)15 MessageId (com.yahoo.pulsar.client.api.MessageId)12 PulsarAdminException (com.yahoo.pulsar.client.admin.PulsarAdminException)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 PersistentSubscription (com.yahoo.pulsar.broker.service.persistent.PersistentSubscription)10 PersistentTopicStats (com.yahoo.pulsar.common.policies.data.PersistentTopicStats)10 BacklogQuota (com.yahoo.pulsar.common.policies.data.BacklogQuota)9 HashSet (java.util.HashSet)9 MockedPulsarServiceBaseTest (com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)8 Field (java.lang.reflect.Field)7