Search in sources :

Example 51 with ConsumerConfiguration

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

the class ZeroQueueSizeTest method zeroQueueSizePartitionedTopicInCompatibility.

@Test(expectedExceptions = PulsarClientException.class)
public void zeroQueueSizePartitionedTopicInCompatibility() throws PulsarClientException, PulsarAdminException {
    String key = "zeroQueueSizePartitionedTopicInCompatibility";
    final String topicName = "persistent://prop/use/ns-abc/topic-" + key;
    final String subscriptionName = "my-ex-subscription-" + key;
    int numberOfPartitions = 3;
    admin.persistentTopics().createPartitionedTopic(topicName, numberOfPartitions);
    ConsumerConfiguration configuration = new ConsumerConfiguration();
    configuration.setReceiverQueueSize(0);
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName, configuration);
}
Also used : Consumer(com.yahoo.pulsar.client.api.Consumer) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) Test(org.testng.annotations.Test)

Example 52 with ConsumerConfiguration

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

Example 53 with ConsumerConfiguration

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

the class AdminApiTest method testPersistentTopicExpireMessageOnParitionTopic.

/**
     * Verify: PersistentTopics.expireMessages()/expireMessagesForAllSubscriptions() for PartitionTopic
     *
     * @throws Exception
     */
@Test
public void testPersistentTopicExpireMessageOnParitionTopic() throws Exception {
    admin.persistentTopics().createPartitionedTopic("persistent://prop-xyz/use/ns1/ds1", 4);
    // create consumer and subscription
    URL pulsarUrl = new URL("http://127.0.0.1" + ":" + BROKER_WEBSERVICE_PORT);
    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setStatsInterval(0, TimeUnit.SECONDS);
    PulsarClient client = PulsarClient.create(pulsarUrl.toString(), clientConf);
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Exclusive);
    Consumer consumer = client.subscribe("persistent://prop-xyz/use/ns1/ds1", "my-sub", conf);
    ProducerConfiguration prodConf = new ProducerConfiguration();
    prodConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    Producer producer = client.createProducer("persistent://prop-xyz/use/ns1/ds1", prodConf);
    for (int i = 0; i < 10; i++) {
        String message = "message-" + i;
        producer.send(message.getBytes());
    }
    PartitionedTopicStats topicStats = admin.persistentTopics().getPartitionedStats("persistent://prop-xyz/use/ns1/ds1", true);
    assertEquals(topicStats.subscriptions.get("my-sub").msgBacklog, 10);
    PersistentTopicStats partitionStatsPartition0 = topicStats.partitions.get("persistent://prop-xyz/use/ns1/ds1-partition-0");
    PersistentTopicStats partitionStatsPartition1 = topicStats.partitions.get("persistent://prop-xyz/use/ns1/ds1-partition-1");
    assertEquals(partitionStatsPartition0.subscriptions.get("my-sub").msgBacklog, 3, 1);
    assertEquals(partitionStatsPartition1.subscriptions.get("my-sub").msgBacklog, 3, 1);
    Thread.sleep(1000);
    admin.persistentTopics().expireMessagesForAllSubscriptions("persistent://prop-xyz/use/ns1/ds1", 1);
    Thread.sleep(1000);
    topicStats = admin.persistentTopics().getPartitionedStats("persistent://prop-xyz/use/ns1/ds1", true);
    partitionStatsPartition0 = topicStats.partitions.get("persistent://prop-xyz/use/ns1/ds1-partition-0");
    partitionStatsPartition1 = topicStats.partitions.get("persistent://prop-xyz/use/ns1/ds1-partition-1");
    assertEquals(partitionStatsPartition0.subscriptions.get("my-sub").msgBacklog, 0);
    assertEquals(partitionStatsPartition1.subscriptions.get("my-sub").msgBacklog, 0);
    producer.close();
    consumer.close();
    client.close();
}
Also used : Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) PartitionedTopicStats(com.yahoo.pulsar.common.policies.data.PartitionedTopicStats) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) URL(java.net.URL) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 54 with ConsumerConfiguration

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

the class AdminApiTest method testPulsarAdminForUriAndUrlEncoding.

/**
     * This test-case verifies that broker should support both url/uri encoding for topic-name. It calls below api with
     * url-encoded and also uri-encoded topic-name in http request: a. PartitionedMetadataLookup b. TopicLookup c. Topic
     * Stats
     * 
     * @param topicName
     * @throws Exception
     */
@Test(dataProvider = "topicName")
public void testPulsarAdminForUriAndUrlEncoding(String topicName) throws Exception {
    final String ns1 = "prop-xyz/use/ns1";
    final String dn1 = "persistent://" + ns1 + "/" + topicName;
    final String urlEncodedTopic = Codec.encode(topicName);
    final String uriEncodedTopic = urlEncodedTopic.replaceAll("\\+", "%20");
    final int numOfPartitions = 4;
    admin.persistentTopics().createPartitionedTopic(dn1, numOfPartitions);
    // Create a consumer to get stats on this topic
    Consumer consumer1 = pulsarClient.subscribe(dn1, "my-subscriber-name", new ConsumerConfiguration());
    PersistentTopicsImpl persistent = (PersistentTopicsImpl) admin.persistentTopics();
    Field field = PersistentTopicsImpl.class.getDeclaredField("persistentTopics");
    field.setAccessible(true);
    WebTarget persistentTopics = (WebTarget) field.get(persistent);
    // (1) Get PartitionedMetadata : with Url and Uri encoding
    final CompletableFuture<PartitionedTopicMetadata> urlEncodedPartitionedMetadata = new CompletableFuture<>();
    // (a) Url encoding
    persistent.asyncGetRequest(persistentTopics.path(ns1).path(urlEncodedTopic).path("partitions"), new InvocationCallback<PartitionedTopicMetadata>() {

        @Override
        public void completed(PartitionedTopicMetadata response) {
            urlEncodedPartitionedMetadata.complete(response);
        }

        @Override
        public void failed(Throwable e) {
            Assert.fail(e.getMessage());
        }
    });
    final CompletableFuture<PartitionedTopicMetadata> uriEncodedPartitionedMetadata = new CompletableFuture<>();
    // (b) Uri encoding
    persistent.asyncGetRequest(persistentTopics.path(ns1).path(uriEncodedTopic).path("partitions"), new InvocationCallback<PartitionedTopicMetadata>() {

        @Override
        public void completed(PartitionedTopicMetadata response) {
            uriEncodedPartitionedMetadata.complete(response);
        }

        @Override
        public void failed(Throwable e) {
            uriEncodedPartitionedMetadata.completeExceptionally(e);
        }
    });
    assertEquals(urlEncodedPartitionedMetadata.get().partitions, numOfPartitions);
    assertEquals(urlEncodedPartitionedMetadata.get().partitions, (uriEncodedPartitionedMetadata.get().partitions));
    // (2) Get Topic Lookup
    LookupImpl lookup = (LookupImpl) admin.lookups();
    Field field2 = LookupImpl.class.getDeclaredField("v2lookup");
    field2.setAccessible(true);
    WebTarget target2 = (WebTarget) field2.get(lookup);
    // (a) Url encoding
    LookupData urlEncodedLookupData = lookup.request(target2.path("/destination/persistent").path(ns1 + "/" + urlEncodedTopic)).get(LookupData.class);
    // (b) Uri encoding
    LookupData uriEncodedLookupData = lookup.request(target2.path("/destination/persistent").path(ns1 + "/" + uriEncodedTopic)).get(LookupData.class);
    Assert.assertNotNull(urlEncodedLookupData.getBrokerUrl());
    assertEquals(urlEncodedLookupData.getBrokerUrl(), uriEncodedLookupData.getBrokerUrl());
    // (3) Get Topic Stats
    final CompletableFuture<PersistentTopicStats> urlStats = new CompletableFuture<>();
    // (a) Url encoding
    persistent.asyncGetRequest(persistentTopics.path(ns1).path(urlEncodedTopic + "-partition-1").path("stats"), new InvocationCallback<PersistentTopicStats>() {

        @Override
        public void completed(PersistentTopicStats response) {
            urlStats.complete(response);
        }

        @Override
        public void failed(Throwable e) {
            urlStats.completeExceptionally(e);
        }
    });
    // (b) Uri encoding
    final CompletableFuture<PersistentTopicStats> uriStats = new CompletableFuture<>();
    persistent.asyncGetRequest(persistentTopics.path(ns1).path(uriEncodedTopic + "-partition-1").path("stats"), new InvocationCallback<PersistentTopicStats>() {

        @Override
        public void completed(PersistentTopicStats response) {
            uriStats.complete(response);
        }

        @Override
        public void failed(Throwable e) {
            uriStats.completeExceptionally(e);
        }
    });
    assertEquals(urlStats.get().subscriptions.size(), 1);
    assertEquals(uriStats.get().subscriptions.size(), 1);
}
Also used : PersistentTopicsImpl(com.yahoo.pulsar.client.admin.internal.PersistentTopicsImpl) LookupData(com.yahoo.pulsar.common.lookup.data.LookupData) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) Field(java.lang.reflect.Field) LookupImpl(com.yahoo.pulsar.client.admin.internal.LookupImpl) CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(com.yahoo.pulsar.client.api.Consumer) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) WebTarget(javax.ws.rs.client.WebTarget) PartitionedTopicMetadata(com.yahoo.pulsar.common.partition.PartitionedTopicMetadata) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 55 with ConsumerConfiguration

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

the class AdminApiTest method testNamespaceUnloadBundle.

@Test
public void testNamespaceUnloadBundle() throws Exception {
    assertEquals(admin.persistentTopics().getList("prop-xyz/use/ns1"), Lists.newArrayList());
    // Force to create a destination
    publishMessagesOnPersistentTopic("persistent://prop-xyz/use/ns1/ds2", 0);
    assertEquals(admin.persistentTopics().getList("prop-xyz/use/ns1"), Lists.newArrayList("persistent://prop-xyz/use/ns1/ds2"));
    // create consumer and subscription
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Exclusive);
    Consumer consumer = pulsarClient.subscribe("persistent://prop-xyz/use/ns1/ds2", "my-sub", conf);
    assertEquals(admin.persistentTopics().getSubscriptions("persistent://prop-xyz/use/ns1/ds2"), Lists.newArrayList("my-sub"));
    // Create producer
    Producer producer = pulsarClient.createProducer("persistent://prop-xyz/use/ns1/ds2");
    for (int i = 0; i < 10; i++) {
        String message = "message-" + i;
        producer.send(message.getBytes());
    }
    consumer.close();
    producer.close();
    try {
        admin.namespaces().unloadNamespaceBundle("prop-xyz/use/ns1", "0x00000000_0xffffffff");
    } catch (Exception e) {
        fail("Unload shouldn't have throw exception");
    }
    // check that no one owns the namespace
    NamespaceBundle bundle = bundleFactory.getBundle(new NamespaceName("prop-xyz/use/ns1"), Range.range(0L, BoundType.CLOSED, 0xffffffffL, BoundType.CLOSED));
    assertFalse(pulsar.getNamespaceService().isServiceUnitOwned(bundle));
    assertFalse(otherPulsar.getNamespaceService().isServiceUnitOwned(bundle));
    pulsarClient.shutdown();
    LOG.info("--- RELOAD ---");
    // Force reload of namespace and wait for topic to be ready
    for (int i = 0; i < 30; i++) {
        try {
            admin.persistentTopics().getStats("persistent://prop-xyz/use/ns1/ds2");
            break;
        } catch (PulsarAdminException e) {
            LOG.warn("Failed to get topic stats.. {}", e.getMessage());
            Thread.sleep(1000);
        }
    }
    admin.persistentTopics().deleteSubscription("persistent://prop-xyz/use/ns1/ds2", "my-sub");
    admin.persistentTopics().delete("persistent://prop-xyz/use/ns1/ds2");
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) NotAuthorizedException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotAuthorizedException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) ConflictException(com.yahoo.pulsar.client.admin.PulsarAdminException.ConflictException) PulsarServerException(com.yahoo.pulsar.broker.PulsarServerException) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Aggregations

ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)92 Test (org.testng.annotations.Test)82 Consumer (com.yahoo.pulsar.client.api.Consumer)74 Producer (com.yahoo.pulsar.client.api.Producer)51 Message (com.yahoo.pulsar.client.api.Message)47 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)26 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)25 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)24 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)15 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)14 PersistentSubscription (com.yahoo.pulsar.broker.service.persistent.PersistentSubscription)12 MockedPulsarServiceBaseTest (com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)11 PulsarAdminException (com.yahoo.pulsar.client.admin.PulsarAdminException)8 CompletableFuture (java.util.concurrent.CompletableFuture)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 IOException (java.io.IOException)7 HashSet (java.util.HashSet)7 LookupException (com.yahoo.pulsar.client.api.PulsarClientException.LookupException)6 PersistentTopicStats (com.yahoo.pulsar.common.policies.data.PersistentTopicStats)6 Field (java.lang.reflect.Field)6