Search in sources :

Example 1 with MessageListener

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

the class BrokerClientIntegrationTest method testResetCursor.

@Test(timeOut = 10000, dataProvider = "subType")
public void testResetCursor(SubscriptionType subType) throws Exception {
    final RetentionPolicies policy = new RetentionPolicies(60, 52 * 1024);
    final DestinationName destName = DestinationName.get("persistent://my-property/use/my-ns/unacked-topic");
    final int warmup = 20;
    final int testSize = 150;
    final List<Message> received = new ArrayList<Message>();
    final ConsumerConfiguration consConfig = new ConsumerConfiguration();
    final String subsId = "sub";
    final NavigableMap<Long, TimestampEntryCount> publishTimeIdMap = new ConcurrentSkipListMap<>();
    consConfig.setSubscriptionType(subType);
    consConfig.setMessageListener((MessageListener) (Consumer consumer, Message msg) -> {
        try {
            synchronized (received) {
                received.add(msg);
            }
            consumer.acknowledge(msg);
            long publishTime = ((MessageImpl) msg).getPublishTime();
            log.info(" publish time is " + publishTime + "," + msg.getMessageId());
            TimestampEntryCount timestampEntryCount = publishTimeIdMap.computeIfAbsent(publishTime, (k) -> new TimestampEntryCount(publishTime));
            timestampEntryCount.incrementAndGet();
        } catch (final PulsarClientException e) {
            log.warn("Failed to ack!");
        }
    });
    admin.namespaces().setRetention(destName.getNamespace(), policy);
    Consumer consumer = pulsarClient.subscribe(destName.toString(), subsId, consConfig);
    final Producer producer = pulsarClient.createProducer(destName.toString());
    log.info("warm up started for " + destName.toString());
    // send warmup msgs
    byte[] msgBytes = new byte[1000];
    for (Integer i = 0; i < warmup; i++) {
        producer.send(msgBytes);
    }
    log.info("warm up finished.");
    // sleep to ensure receiving of msgs
    for (int n = 0; n < 10 && received.size() < warmup; n++) {
        Thread.sleep(100);
    }
    // validate received msgs
    Assert.assertEquals(received.size(), warmup);
    received.clear();
    // publish testSize num of msgs
    log.info("Sending more messages.");
    for (Integer n = 0; n < testSize; n++) {
        producer.send(msgBytes);
        Thread.sleep(1);
    }
    log.info("Sending more messages done.");
    Thread.sleep(3000);
    long begints = publishTimeIdMap.firstEntry().getKey();
    long endts = publishTimeIdMap.lastEntry().getKey();
    // find reset timestamp
    long timestamp = (endts - begints) / 2 + begints;
    timestamp = publishTimeIdMap.floorKey(timestamp);
    NavigableMap<Long, TimestampEntryCount> expectedMessages = new ConcurrentSkipListMap<>();
    expectedMessages.putAll(publishTimeIdMap.tailMap(timestamp, true));
    received.clear();
    log.info("reset cursor to " + timestamp + " for topic " + destName.toString() + " for subs " + subsId);
    log.info("issuing admin operation on " + admin.getServiceUrl().toString());
    List<String> subList = admin.persistentTopics().getSubscriptions(destName.toString());
    for (String subs : subList) {
        log.info("got sub " + subs);
    }
    publishTimeIdMap.clear();
    // reset the cursor to this timestamp
    Assert.assertTrue(subList.contains(subsId));
    admin.persistentTopics().resetCursor(destName.toString(), subsId, timestamp);
    consumer = pulsarClient.subscribe(destName.toString(), subsId, consConfig);
    Thread.sleep(3000);
    int totalExpected = 0;
    for (TimestampEntryCount tec : expectedMessages.values()) {
        totalExpected += tec.numMessages;
    }
    // validate that replay happens after the timestamp
    Assert.assertTrue(publishTimeIdMap.firstEntry().getKey() >= timestamp);
    consumer.close();
    producer.close();
    // validate that expected and received counts match
    int totalReceived = 0;
    for (TimestampEntryCount tec : publishTimeIdMap.values()) {
        totalReceived += tec.numMessages;
    }
    Assert.assertEquals(totalReceived, totalExpected, "did not receive all messages on replay after reset");
}
Also used : RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) Assert.assertNull(org.testng.Assert.assertNull) DataProvider(org.testng.annotations.DataProvider) Consumer(com.yahoo.pulsar.client.api.Consumer) LoggerFactory(org.slf4j.LoggerFactory) Test(org.testng.annotations.Test) Mockito.spy(org.mockito.Mockito.spy) AfterMethod(org.testng.annotations.AfterMethod) OwnershipCache(com.yahoo.pulsar.broker.namespace.OwnershipCache) SubscriptionType(com.yahoo.pulsar.client.api.SubscriptionType) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) ArrayList(java.util.ArrayList) State(com.yahoo.pulsar.client.impl.HandlerBase.State) Assert(org.testng.Assert) ProducerConsumerBase(com.yahoo.pulsar.client.api.ProducerConsumerBase) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) Matchers.anyObject(org.mockito.Matchers.anyObject) Mockito.doAnswer(org.mockito.Mockito.doAnswer) MessageListener(com.yahoo.pulsar.client.api.MessageListener) URI(java.net.URI) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) Assert.assertFalse(org.testng.Assert.assertFalse) ExecutorService(java.util.concurrent.ExecutorService) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Logger(org.slf4j.Logger) Producer(com.yahoo.pulsar.client.api.Producer) Assert.fail(org.testng.Assert.fail) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) BeforeMethod(org.testng.annotations.BeforeMethod) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) Set(java.util.Set) PulsarHandler(com.yahoo.pulsar.common.api.PulsarHandler) Field(java.lang.reflect.Field) NavigableMap(java.util.NavigableMap) Executors(java.util.concurrent.Executors) Sets(com.google.common.collect.Sets) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Topic(com.yahoo.pulsar.broker.service.Topic) Mockito.never(org.mockito.Mockito.never) List(java.util.List) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) ConcurrentLongHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentLongHashMap) Assert.assertTrue(org.testng.Assert.assertTrue) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Message(com.yahoo.pulsar.client.api.Message) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) Message(com.yahoo.pulsar.client.api.Message) ArrayList(java.util.ArrayList) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Test(org.testng.annotations.Test)

Example 2 with MessageListener

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

the class SampleConsumerListener method main.

public static void main(String[] args) throws PulsarClientException, InterruptedException, IOException {
    PulsarClient pulsarClient = PulsarClient.create("http://localhost:8080");
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setMessageListener(new MessageListener() {

        public void received(Consumer consumer, Message msg) {
            log.info("Received message: {}", msg);
            consumer.acknowledgeAsync(msg);
        }
    });
    pulsarClient.subscribe("persistent://my-property/use/my-ns/my-topic", "my-subscriber-name", conf);
    // Block main thread
    System.in.read();
    pulsarClient.close();
}
Also used : Consumer(com.yahoo.pulsar.client.api.Consumer) Message(com.yahoo.pulsar.client.api.Message) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) MessageListener(com.yahoo.pulsar.client.api.MessageListener) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient)

Example 3 with MessageListener

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

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 destination 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);
        }
    }
    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar performance consumer with config: {}", w.writeValueAsString(arguments));
    final DestinationName prefixDestinationName = DestinationName.get(arguments.topic.get(0));
    final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;
    MessageListener listener = new MessageListener() {

        public void received(Consumer consumer, Message msg) {
            messagesReceived.increment();
            bytesReceived.add(msg.getData().length);
            if (limiter != null) {
                limiter.acquire();
            }
            consumer.acknowledgeAsync(msg);
        }
    };
    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new DefaultThreadFactory("pulsar-perf-consumer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-consumer"));
    }
    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient pulsarClient = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);
    List<Future<Consumer>> futures = Lists.newArrayList();
    ConsumerConfiguration consumerConfig = new ConsumerConfiguration();
    consumerConfig.setMessageListener(listener);
    consumerConfig.setReceiverQueueSize(arguments.receiverQueueSize);
    for (int i = 0; i < arguments.numDestinations; i++) {
        final DestinationName destinationName = (arguments.numDestinations == 1) ? prefixDestinationName : DestinationName.get(String.format("%s-%d", prefixDestinationName, i));
        log.info("Adding {} consumers on destination {}", arguments.numConsumers, destinationName);
        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(pulsarClient.subscribeAsync(destinationName.toString(), subscriberName, consumerConfig));
        }
    }
    for (Future<Consumer> future : futures) {
        future.get();
    }
    log.info("Start receiving from {} consumers on {} destinations", arguments.numConsumers, arguments.numDestinations);
    long oldTime = System.nanoTime();
    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;
        log.info("Throughput received: {}  msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
        oldTime = now;
    }
    pulsarClient.close();
}
Also used : Message(com.yahoo.pulsar.client.api.Message) MessageListener(com.yahoo.pulsar.client.api.MessageListener) Properties(java.util.Properties) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) Consumer(com.yahoo.pulsar.client.api.Consumer) JCommander(com.beust.jcommander.JCommander) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) ParameterException(com.beust.jcommander.ParameterException) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) Future(java.util.concurrent.Future) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration)

Aggregations

Consumer (com.yahoo.pulsar.client.api.Consumer)3 ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)3 Message (com.yahoo.pulsar.client.api.Message)3 MessageListener (com.yahoo.pulsar.client.api.MessageListener)3 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)3 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)2 DestinationName (com.yahoo.pulsar.common.naming.DestinationName)2 JCommander (com.beust.jcommander.JCommander)1 ParameterException (com.beust.jcommander.ParameterException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 Sets (com.google.common.collect.Sets)1 RateLimiter (com.google.common.util.concurrent.RateLimiter)1 OwnershipCache (com.yahoo.pulsar.broker.namespace.OwnershipCache)1 Topic (com.yahoo.pulsar.broker.service.Topic)1 Producer (com.yahoo.pulsar.client.api.Producer)1 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)1 ProducerConsumerBase (com.yahoo.pulsar.client.api.ProducerConsumerBase)1 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)1 SubscriptionType (com.yahoo.pulsar.client.api.SubscriptionType)1