Search in sources :

Example 1 with MessageListener

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

the class TopicTerminationTest method testSimpleTerminationMessageListener.

@Test(timeOut = 20000)
public void testSimpleTerminationMessageListener() throws Exception {
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
    CountDownLatch latch = new CountDownLatch(1);
    org.apache.pulsar.client.api.Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName).subscriptionName("my-sub").messageListener(new MessageListener<byte[]>() {

        @Override
        public void received(Consumer<byte[]> consumer, Message<byte[]> msg) {
        // do nothing
        }

        @Override
        public void reachedEndOfTopic(Consumer<byte[]> consumer) {
            latch.countDown();
            assertTrue(consumer.hasReachedEndOfTopic());
        }
    }).subscribe();
    /* MessageId msgId1 = */
    producer.send("test-msg-1".getBytes());
    /* MessageId msgId2 = */
    producer.send("test-msg-2".getBytes());
    MessageId msgId3 = producer.send("test-msg-3".getBytes());
    consumer.acknowledgeCumulative(msgId3);
    Thread.sleep(100);
    assertFalse(consumer.hasReachedEndOfTopic());
    MessageId lastMessageId = admin.persistentTopics().terminateTopicAsync(topicName).get();
    assertEquals(lastMessageId, msgId3);
    assertTrue(latch.await(3, TimeUnit.SECONDS));
    assertTrue(consumer.hasReachedEndOfTopic());
}
Also used : Consumer(org.apache.pulsar.client.api.Consumer) Message(org.apache.pulsar.client.api.Message) MessageListener(org.apache.pulsar.client.api.MessageListener) CountDownLatch(java.util.concurrent.CountDownLatch) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 2 with MessageListener

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

the class PerformanceConsumer method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-consumer");
    try {
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }
    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }
    if (arguments.topic.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }
    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }
        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }
        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }
        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
        if (arguments.useTls == false) {
            arguments.useTls = Boolean.parseBoolean(prop.getProperty("useTls"));
        }
        if (isBlank(arguments.tlsTrustCertsFilePath)) {
            arguments.tlsTrustCertsFilePath = prop.getProperty("tlsTrustCertsFilePath", "");
        }
    }
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar performance consumer with config: {}", w.writeValueAsString(arguments));
    final TopicName prefixTopicName = TopicName.get(arguments.topic.get(0));
    final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;
    MessageListener<byte[]> listener = (consumer, msg) -> {
        messagesReceived.increment();
        bytesReceived.add(msg.getData().length);
        if (limiter != null) {
            limiter.acquire();
        }
        long latencyMillis = System.currentTimeMillis() - msg.getPublishTime();
        if (latencyMillis >= 0) {
            recorder.recordValue(latencyMillis);
            cumulativeRecorder.recordValue(latencyMillis);
        }
        consumer.acknowledgeAsync(msg);
    };
    ClientBuilder clientBuilder = // 
    PulsarClient.builder().serviceUrl(// 
    arguments.serviceURL).connectionsPerBroker(// 
    arguments.maxConnections).statsInterval(arguments.statsIntervalSeconds, // 
    TimeUnit.SECONDS).ioThreads(// 
    Runtime.getRuntime().availableProcessors()).enableTls(// 
    arguments.useTls).tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient pulsarClient = clientBuilder.build();
    class EncKeyReader implements CryptoKeyReader {

        EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();

        EncKeyReader(byte[] value) {
            keyInfo.setKey(value);
        }

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            return null;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            if (keyName.equals(arguments.encKeyName)) {
                return keyInfo;
            }
            return null;
        }
    }
    List<Future<Consumer<byte[]>>> futures = Lists.newArrayList();
    ConsumerBuilder<byte[]> consumerBuilder = // 
    pulsarClient.newConsumer().messageListener(// 
    listener).receiverQueueSize(// 
    arguments.receiverQueueSize).subscriptionType(arguments.subscriptionType);
    if (arguments.encKeyName != null) {
        byte[] pKey = Files.readAllBytes(Paths.get(arguments.encKeyFile));
        EncKeyReader keyReader = new EncKeyReader(pKey);
        consumerBuilder.cryptoKeyReader(keyReader);
    }
    for (int i = 0; i < arguments.numTopics; i++) {
        final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
        log.info("Adding {} consumers on topic {}", arguments.numConsumers, topicName);
        for (int j = 0; j < arguments.numConsumers; j++) {
            String subscriberName;
            if (arguments.numConsumers > 1) {
                subscriberName = String.format("%s-%d", arguments.subscriberName, j);
            } else {
                subscriberName = arguments.subscriberName;
            }
            futures.add(consumerBuilder.clone().topic(topicName.toString()).subscriptionName(subscriberName).subscribeAsync());
        }
    }
    for (Future<Consumer<byte[]>> future : futures) {
        future.get();
    }
    log.info("Start receiving from {} consumers on {} topics", arguments.numConsumers, arguments.numTopics);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        public void run() {
            printAggregatedStats();
        }
    });
    long oldTime = System.nanoTime();
    Histogram reportHistogram = null;
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }
        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesReceived.sumThenReset() / elapsed;
        double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024;
        reportHistogram = recorder.getIntervalHistogram(reportHistogram);
        log.info("Throughput received: {}  msg/s -- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", dec.format(rate), dec.format(throughput), dec.format(reportHistogram.getMean()), (long) reportHistogram.getValueAtPercentile(50), (long) reportHistogram.getValueAtPercentile(95), (long) reportHistogram.getValueAtPercentile(99), (long) reportHistogram.getValueAtPercentile(99.9), (long) reportHistogram.getValueAtPercentile(99.99), (long) reportHistogram.getMaxValue());
        reportHistogram.reset();
        oldTime = now;
    }
    pulsarClient.close();
}
Also used : LongAdder(java.util.concurrent.atomic.LongAdder) TopicName(org.apache.pulsar.common.naming.TopicName) ParameterException(com.beust.jcommander.ParameterException) Parameter(com.beust.jcommander.Parameter) LoggerFactory(org.slf4j.LoggerFactory) ConsumerBuilder(org.apache.pulsar.client.api.ConsumerBuilder) RateLimiter(com.google.common.util.concurrent.RateLimiter) Future(java.util.concurrent.Future) Lists(com.google.common.collect.Lists) Map(java.util.Map) Recorder(org.HdrHistogram.Recorder) EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Properties(java.util.Properties) Logger(org.slf4j.Logger) Files(java.nio.file.Files) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) MessageListener(org.apache.pulsar.client.api.MessageListener) DecimalFormat(java.text.DecimalFormat) JCommander(com.beust.jcommander.JCommander) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileInputStream(java.io.FileInputStream) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) TimeUnit(java.util.concurrent.TimeUnit) Histogram(org.HdrHistogram.Histogram) Consumer(org.apache.pulsar.client.api.Consumer) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) Paths(java.nio.file.Paths) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) Histogram(org.HdrHistogram.Histogram) EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) Properties(java.util.Properties) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) Consumer(org.apache.pulsar.client.api.Consumer) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) TopicName(org.apache.pulsar.common.naming.TopicName) Future(java.util.concurrent.Future) Map(java.util.Map)

Aggregations

Consumer (org.apache.pulsar.client.api.Consumer)2 MessageListener (org.apache.pulsar.client.api.MessageListener)2 JCommander (com.beust.jcommander.JCommander)1 Parameter (com.beust.jcommander.Parameter)1 ParameterException (com.beust.jcommander.ParameterException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 Lists (com.google.common.collect.Lists)1 RateLimiter (com.google.common.util.concurrent.RateLimiter)1 FileInputStream (java.io.FileInputStream)1 Files (java.nio.file.Files)1 Paths (java.nio.file.Paths)1 DecimalFormat (java.text.DecimalFormat)1 List (java.util.List)1 Map (java.util.Map)1 Properties (java.util.Properties)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Future (java.util.concurrent.Future)1 TimeUnit (java.util.concurrent.TimeUnit)1 LongAdder (java.util.concurrent.atomic.LongAdder)1