Search in sources :

Example 16 with PulsarClient

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

the class SampleAsyncProducer method main.

public static void main(String[] args) throws PulsarClientException, InterruptedException, IOException {
    PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("http://localhost:8080").build();
    Producer<byte[]> producer = pulsarClient.newProducer().topic("persistent://my-property/use/my-ns/my-topic").sendTimeout(3, TimeUnit.SECONDS).create();
    List<CompletableFuture<MessageId>> futures = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
        final String content = "my-message-" + i;
        CompletableFuture<MessageId> future = producer.sendAsync(content.getBytes());
        future.handle((v, ex) -> {
            if (ex == null) {
                log.info("Message persisted: {}", content);
            } else {
                log.error("Error persisting message: {}", content, ex);
            }
            return null;
        });
        futures.add(future);
    }
    log.info("Waiting for async ops to complete");
    for (CompletableFuture<MessageId> future : futures) {
        future.join();
    }
    log.info("All operations completed");
    pulsarClient.close();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) PulsarClient(org.apache.pulsar.client.api.PulsarClient) MessageId(org.apache.pulsar.client.api.MessageId)

Example 17 with PulsarClient

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

the class SampleConsumerListener method main.

public static void main(String[] args) throws PulsarClientException, InterruptedException, IOException {
    PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("http://localhost:8080").build();
    // 
    pulsarClient.newConsumer().topic(// 
    "persistent://my-property/use/my-ns/my-topic").subscriptionName(// 
    "my-subscription-name").messageListener((consumer, msg) -> {
        log.info("Received message: {}", msg);
        consumer.acknowledgeAsync(msg);
    }).subscribe();
    // Block main thread
    System.in.read();
    pulsarClient.close();
}
Also used : Slf4j(lombok.extern.slf4j.Slf4j) IOException(java.io.IOException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) PulsarClient(org.apache.pulsar.client.api.PulsarClient)

Example 18 with PulsarClient

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

the class SampleCryptoConsumer method main.

public static void main(String[] args) throws PulsarClientException, InterruptedException {
    class RawFileKeyReader implements CryptoKeyReader {

        String publicKeyFile = "";

        String privateKeyFile = "";

        RawFileKeyReader(String pubKeyFile, String privKeyFile) {
            publicKeyFile = pubKeyFile;
            privateKeyFile = privKeyFile;
        }

        @Override
        public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
            // Read the public key from the file
            EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
            try {
                keyInfo.setKey(Files.readAllBytes(Paths.get(publicKeyFile)));
            } catch (IOException e) {
                log.error("Failed to read public key from file {}", publicKeyFile, e);
            }
            return keyInfo;
        }

        @Override
        public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
            // Read the private key from the file
            EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
            try {
                keyInfo.setKey(Files.readAllBytes(Paths.get(privateKeyFile)));
            } catch (IOException e) {
                log.error("Failed to read private key from file {}", privateKeyFile, e);
            }
            return keyInfo;
        }
    }
    // Create pulsar client
    PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("http://127.0.0.1:8080").build();
    Consumer<byte[]> consumer = pulsarClient.newConsumer().topic("persistent://my-property/use/my-ns/my-topic").subscriptionName("my-subscription-name").cryptoKeyReader(new RawFileKeyReader("test_ecdsa_pubkey.pem", "test_ecdsa_privkey.pem")).subscribe();
    Message<byte[]> msg = null;
    for (int i = 0; i < 10; i++) {
        msg = consumer.receive();
        // process the messsage
        log.info("Received: {}", new String(msg.getData()));
    }
    // Acknowledge the consumption of all messages at once
    consumer.acknowledgeCumulative(msg);
    pulsarClient.close();
}
Also used : EncryptionKeyInfo(org.apache.pulsar.client.api.EncryptionKeyInfo) IOException(java.io.IOException) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Map(java.util.Map) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader)

Example 19 with PulsarClient

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

the class PerformanceReader method main.

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-reader");
    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 reader 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;
    ReaderListener<byte[]> listener = (reader, msg) -> {
        messagesReceived.increment();
        bytesReceived.add(msg.getData().length);
        if (limiter != null) {
            limiter.acquire();
        }
    };
    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();
    List<CompletableFuture<Reader<byte[]>>> futures = Lists.newArrayList();
    MessageId startMessageId;
    if ("earliest".equals(arguments.startMessageId)) {
        startMessageId = MessageId.earliest;
    } else if ("latest".equals(arguments.startMessageId)) {
        startMessageId = MessageId.latest;
    } else {
        String[] parts = arguments.startMessageId.split(":");
        startMessageId = new MessageIdImpl(Long.parseLong(parts[0]), Long.parseLong(parts[1]), -1);
    }
    ReaderBuilder<byte[]> readerBuilder = // 
    pulsarClient.newReader().readerListener(// 
    listener).receiverQueueSize(// 
    arguments.receiverQueueSize).startMessageId(startMessageId);
    for (int i = 0; i < arguments.numTopics; i++) {
        final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
        futures.add(readerBuilder.clone().topic(topicName.toString()).createAsync());
    }
    FutureUtil.waitForAll(futures).get();
    log.info("Start reading from {} topics", arguments.numTopics);
    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("Read throughput: {}  msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
        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) CompletableFuture(java.util.concurrent.CompletableFuture) RateLimiter(com.google.common.util.concurrent.RateLimiter) ReaderListener(org.apache.pulsar.client.api.ReaderListener) Lists(com.google.common.collect.Lists) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Properties(java.util.Properties) Logger(org.slf4j.Logger) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) DecimalFormat(java.text.DecimalFormat) JCommander(com.beust.jcommander.JCommander) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Reader(org.apache.pulsar.client.api.Reader) FileInputStream(java.io.FileInputStream) TimeUnit(java.util.concurrent.TimeUnit) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) MessageId(org.apache.pulsar.client.api.MessageId) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) ReaderBuilder(org.apache.pulsar.client.api.ReaderBuilder) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) RateLimiter(com.google.common.util.concurrent.RateLimiter) TopicName(org.apache.pulsar.common.naming.TopicName) CompletableFuture(java.util.concurrent.CompletableFuture) 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) MessageId(org.apache.pulsar.client.api.MessageId)

Example 20 with PulsarClient

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

the class ProxyTest method testProducer.

@Test
public void testProducer() throws Exception {
    PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://localhost:" + proxyConfig.getServicePort()).build();
    Producer<byte[]> producer = client.newProducer().topic("persistent://sample/test/local/producer-topic").create();
    for (int i = 0; i < 10; i++) {
        producer.send("test".getBytes());
    }
    client.close();
}
Also used : PulsarClient(org.apache.pulsar.client.api.PulsarClient) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Aggregations

PulsarClient (org.apache.pulsar.client.api.PulsarClient)86 Test (org.testng.annotations.Test)69 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)27 MockedPulsarServiceBaseTest (org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)14 IOException (java.io.IOException)12 PersistentTopicStats (org.apache.pulsar.common.policies.data.PersistentTopicStats)12 PropertyAdmin (org.apache.pulsar.common.policies.data.PropertyAdmin)12 URL (java.net.URL)9 LinkedList (java.util.LinkedList)9 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)9 BacklogQuota (org.apache.pulsar.common.policies.data.BacklogQuota)9 Function (org.apache.pulsar.functions.proto.Function)9 CountDownLatch (java.util.concurrent.CountDownLatch)8 Map (java.util.Map)7 Producer (org.apache.pulsar.client.api.Producer)7 Reader (org.apache.pulsar.client.api.Reader)7 ReaderBuilder (org.apache.pulsar.client.api.ReaderBuilder)7 URI (java.net.URI)6 HashMap (java.util.HashMap)6 CompletableFuture (java.util.concurrent.CompletableFuture)6