Search in sources :

Example 16 with ProducerConfiguration

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

the class MultiConsumersOneOutputTopicProducersTest method setup.

@BeforeMethod
public void setup() throws Exception {
    this.mockClient = mock(PulsarClient.class);
    when(mockClient.createProducer(anyString(), any(ProducerConfiguration.class))).thenAnswer(invocationOnMock -> {
        ProducerConfiguration conf = invocationOnMock.getArgumentAt(1, ProducerConfiguration.class);
        String producerName = conf.getProducerName();
        synchronized (mockProducers) {
            Producer producer = mockProducers.get(producerName);
            if (null == producer) {
                producer = createMockProducer(producerName);
                mockProducers.put(producerName, producer);
            }
            return producer;
        }
    });
    producers = new MultiConsumersOneOuputTopicProducers(mockClient, TEST_OUTPUT_TOPIC);
    producers.initialize();
}
Also used : Producer(org.apache.pulsar.client.api.Producer) ProducerConfiguration(org.apache.pulsar.client.api.ProducerConfiguration) PulsarClient(org.apache.pulsar.client.api.PulsarClient) Matchers.anyString(org.mockito.Matchers.anyString) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 17 with ProducerConfiguration

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

the class AbstractOneOuputTopicProducers method createProducer.

protected Producer createProducer(String topic, String producerName) throws PulsarClientException {
    ProducerConfiguration newConf = newProducerConfiguration();
    newConf.setProducerName(producerName);
    return client.createProducer(topic, newConf);
}
Also used : ProducerConfiguration(org.apache.pulsar.client.api.ProducerConfiguration)

Example 18 with ProducerConfiguration

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

the class AbstractOneOuputTopicProducers method newProducerConfiguration.

protected ProducerConfiguration newProducerConfiguration() {
    ProducerConfiguration conf = new ProducerConfiguration();
    conf.setBlockIfQueueFull(true);
    conf.setBatchingEnabled(true);
    conf.setBatchingMaxPublishDelay(1, TimeUnit.MILLISECONDS);
    conf.setMaxPendingMessages(1000000);
    conf.setCompressionType(CompressionType.LZ4);
    conf.setHashingScheme(HashingScheme.Murmur3_32Hash);
    conf.setMessageRoutingMode(MessageRoutingMode.CustomPartition);
    // use function result router to deal with different processing guarantees.
    conf.setMessageRouter(FunctionResultRouter.of());
    return conf;
}
Also used : ProducerConfiguration(org.apache.pulsar.client.api.ProducerConfiguration)

Example 19 with ProducerConfiguration

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

the class JavaInstanceRunnableProcessTest method setup.

@BeforeMethod
public void setup() throws Exception {
    mockProducers.clear();
    mockConsumers.clear();
    fnConfig = FunctionConfig.newBuilder().setAutoAck(true).setClassName(TestFunction.class.getName()).addInputs("test-src-topic").setName("test-function").setOutput("test-output-topic").setProcessingGuarantees(ProcessingGuarantees.ATLEAST_ONCE).setTenant("test-tenant").setNamespace("test-namespace").build();
    config = new InstanceConfig();
    config.setFunctionId("test-function-id");
    config.setFunctionVersion("v1");
    config.setInstanceId("test-instance-id");
    config.setMaxBufferedTuples(1000);
    config.setFunctionConfig(fnConfig);
    mockClient = mock(PulsarClientImpl.class);
    // mock FunctionCacheManager
    fnCache = mock(FunctionCacheManager.class);
    doNothing().when(fnCache).registerFunctionInstance(anyString(), anyString(), anyList(), anyList());
    doNothing().when(fnCache).unregisterFunctionInstance(anyString(), anyString());
    ClassLoader clsLoader = JavaInstanceRunnableTest.class.getClassLoader();
    when(fnCache.getClassLoader(anyString())).thenReturn(clsLoader);
    // mock producer & consumer
    when(mockClient.createProducer(anyString(), any(ProducerConfiguration.class))).thenAnswer(invocationOnMock -> {
        String topic = invocationOnMock.getArgumentAt(0, String.class);
        ProducerConfiguration conf = invocationOnMock.getArgumentAt(1, ProducerConfiguration.class);
        String producerName = conf.getProducerName();
        Pair<String, String> pair = Pair.of(topic, producerName);
        ProducerInstance producerInstance = mockProducers.get(pair);
        if (null == producerInstance) {
            Producer producer = mock(Producer.class);
            LinkedBlockingQueue<Message> msgQueue = new LinkedBlockingQueue<>();
            final ProducerInstance instance = new ProducerInstance(producer, msgQueue);
            producerInstance = instance;
            when(producer.getProducerName()).thenReturn(producerName);
            when(producer.getTopic()).thenReturn(topic);
            when(producer.sendAsync(any(Message.class))).thenAnswer(invocationOnMock1 -> {
                Message msg = invocationOnMock1.getArgumentAt(0, Message.class);
                log.info("producer send message {}", msg);
                CompletableFuture<MessageId> future = new CompletableFuture<>();
                instance.addSendFuture(future);
                msgQueue.put(msg);
                return future;
            });
            when(producer.closeAsync()).thenReturn(FutureUtils.Void());
            mockProducers.put(pair, producerInstance);
        }
        return producerInstance.getProducer();
    });
    when(mockClient.subscribe(anyString(), anyString(), any(ConsumerConfiguration.class))).thenAnswer(invocationOnMock -> {
        String topic = invocationOnMock.getArgumentAt(0, String.class);
        String subscription = invocationOnMock.getArgumentAt(1, String.class);
        ConsumerConfiguration conf = invocationOnMock.getArgumentAt(2, ConsumerConfiguration.class);
        Pair<String, String> pair = Pair.of(topic, subscription);
        ConsumerInstance consumerInstance = mockConsumers.get(pair);
        if (null == consumerInstance) {
            Consumer consumer = mock(Consumer.class);
            ConsumerInstance instance = new ConsumerInstance(consumer, conf);
            consumerInstance = instance;
            when(consumer.getTopic()).thenReturn(topic);
            when(consumer.getSubscription()).thenReturn(subscription);
            when(consumer.acknowledgeAsync(any(Message.class))).thenAnswer(invocationOnMock1 -> {
                Message msg = invocationOnMock1.getArgumentAt(0, Message.class);
                log.info("Ack message {} : message id = {}", msg, msg.getMessageId());
                instance.removeMessage(msg.getMessageId());
                return FutureUtils.Void();
            });
            when(consumer.acknowledgeCumulativeAsync(any(Message.class))).thenAnswer(invocationOnMock1 -> {
                Message msg = invocationOnMock1.getArgumentAt(0, Message.class);
                log.info("Ack message cumulatively message id = {}", msg, msg.getMessageId());
                instance.removeMessagesBefore(msg.getMessageId());
                return FutureUtils.Void();
            });
            when(consumer.closeAsync()).thenAnswer(invocationOnMock1 -> {
                mockConsumers.remove(pair, instance);
                return FutureUtils.Void();
            });
            doAnswer(invocationOnMock1 -> {
                mockConsumers.remove(pair, instance);
                return null;
            }).when(consumer).close();
            mockConsumers.put(pair, consumerInstance);
        }
        return consumerInstance.getConsumer();
    });
    // 
    // Mock State Store
    // 
    StorageClientBuilder mockBuilder = mock(StorageClientBuilder.class);
    when(mockBuilder.withNamespace(anyString())).thenReturn(mockBuilder);
    when(mockBuilder.withSettings(any(StorageClientSettings.class))).thenReturn(mockBuilder);
    this.mockStorageClient = mock(StorageClient.class);
    when(mockBuilder.build()).thenReturn(mockStorageClient);
    StorageAdminClient adminClient = mock(StorageAdminClient.class);
    when(mockBuilder.buildAdmin()).thenReturn(adminClient);
    PowerMockito.mockStatic(StorageClientBuilder.class);
    PowerMockito.when(StorageClientBuilder.newBuilder()).thenReturn(mockBuilder);
    when(adminClient.getStream(anyString(), anyString())).thenReturn(FutureUtils.value(StreamProperties.newBuilder().build()));
    mockTable = mock(Table.class);
    when(mockStorageClient.openTable(anyString())).thenReturn(FutureUtils.value(mockTable));
    // 
    // Mock Function Stats
    // 
    mockFunctionStats = spy(new FunctionStats());
    PowerMockito.whenNew(FunctionStats.class).withNoArguments().thenReturn(mockFunctionStats);
    // Mock message builder
    PowerMockito.mockStatic(MessageBuilder.class);
    PowerMockito.when(MessageBuilder.create()).thenAnswer(invocationOnMock -> {
        Message msg = mock(Message.class);
        MessageBuilder builder = mock(MessageBuilder.class);
        when(builder.setContent(any(byte[].class))).thenAnswer(invocationOnMock1 -> {
            byte[] content = invocationOnMock1.getArgumentAt(0, byte[].class);
            when(msg.getData()).thenReturn(content);
            return builder;
        });
        when(builder.setSequenceId(anyLong())).thenAnswer(invocationOnMock1 -> {
            long seqId = invocationOnMock1.getArgumentAt(0, long.class);
            when(msg.getSequenceId()).thenReturn(seqId);
            return builder;
        });
        when(builder.setProperty(anyString(), anyString())).thenAnswer(invocationOnMock1 -> {
            String key = invocationOnMock1.getArgumentAt(0, String.class);
            String value = invocationOnMock1.getArgumentAt(1, String.class);
            when(msg.getProperty(eq(key))).thenReturn(value);
            return builder;
        });
        when(builder.build()).thenReturn(msg);
        return builder;
    });
}
Also used : Message(org.apache.pulsar.client.api.Message) ProducerConfiguration(org.apache.pulsar.client.api.ProducerConfiguration) Matchers.anyString(org.mockito.Matchers.anyString) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(org.apache.pulsar.client.api.Consumer) MessageBuilder(org.apache.pulsar.client.api.MessageBuilder) ConsumerConfiguration(org.apache.pulsar.client.api.ConsumerConfiguration) FunctionCacheManager(org.apache.pulsar.functions.utils.functioncache.FunctionCacheManager) Table(org.apache.bookkeeper.api.kv.Table) StorageClientBuilder(org.apache.bookkeeper.clients.StorageClientBuilder) StorageAdminClient(org.apache.bookkeeper.clients.admin.StorageAdminClient) StorageClient(org.apache.bookkeeper.api.StorageClient) StorageClientSettings(org.apache.bookkeeper.clients.config.StorageClientSettings) Producer(org.apache.pulsar.client.api.Producer) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) MessageId(org.apache.pulsar.client.api.MessageId) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 20 with ProducerConfiguration

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

the class ProducerHandler method getProducerConfiguration.

private ProducerConfiguration getProducerConfiguration() {
    ProducerConfiguration conf = new ProducerConfiguration();
    // Set to false to prevent the server thread from being blocked if a lot of messages are pending.
    conf.setBlockIfQueueFull(false);
    if (queryParams.containsKey("producerName")) {
        conf.setProducerName(queryParams.get("producerName"));
    }
    if (queryParams.containsKey("initialSequenceId")) {
        conf.setInitialSequenceId(Long.parseLong("initialSequenceId"));
    }
    if (queryParams.containsKey("hashingScheme")) {
        conf.setHashingScheme(HashingScheme.valueOf(queryParams.get("hashingScheme")));
    }
    if (queryParams.containsKey("sendTimeoutMillis")) {
        conf.setSendTimeout(Integer.parseInt(queryParams.get("sendTimeoutMillis")), TimeUnit.MILLISECONDS);
    }
    if (queryParams.containsKey("batchingEnabled")) {
        conf.setBatchingEnabled(Boolean.parseBoolean(queryParams.get("batchingEnabled")));
    }
    if (queryParams.containsKey("batchingMaxMessages")) {
        conf.setBatchingMaxMessages(Integer.parseInt(queryParams.get("batchingMaxMessages")));
    }
    if (queryParams.containsKey("maxPendingMessages")) {
        conf.setMaxPendingMessages(Integer.parseInt(queryParams.get("maxPendingMessages")));
    }
    if (queryParams.containsKey("batchingMaxPublishDelay")) {
        conf.setBatchingMaxPublishDelay(Integer.parseInt(queryParams.get("batchingMaxPublishDelay")), TimeUnit.MILLISECONDS);
    }
    if (queryParams.containsKey("messageRoutingMode")) {
        checkArgument(Enums.getIfPresent(MessageRoutingMode.class, queryParams.get("messageRoutingMode")).isPresent(), "Invalid messageRoutingMode %s", queryParams.get("messageRoutingMode"));
        MessageRoutingMode routingMode = MessageRoutingMode.valueOf(queryParams.get("messageRoutingMode"));
        if (!MessageRoutingMode.CustomPartition.equals(routingMode)) {
            conf.setMessageRoutingMode(routingMode);
        }
    }
    if (queryParams.containsKey("compressionType")) {
        checkArgument(Enums.getIfPresent(CompressionType.class, queryParams.get("compressionType")).isPresent(), "Invalid compressionType %s", queryParams.get("compressionType"));
        conf.setCompressionType(CompressionType.valueOf(queryParams.get("compressionType")));
    }
    return conf;
}
Also used : MessageRoutingMode(org.apache.pulsar.client.api.ProducerConfiguration.MessageRoutingMode) ProducerConfiguration(org.apache.pulsar.client.api.ProducerConfiguration)

Aggregations

ProducerConfiguration (org.apache.pulsar.client.api.ProducerConfiguration)35 Producer (org.apache.pulsar.client.api.Producer)31 Test (org.testng.annotations.Test)30 ConsumerConfiguration (org.apache.pulsar.client.api.ConsumerConfiguration)29 Consumer (org.apache.pulsar.client.api.Consumer)26 Message (org.apache.pulsar.client.api.Message)26 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)15 IOException (java.io.IOException)14 ExecutionException (java.util.concurrent.ExecutionException)13 MessageId (org.apache.pulsar.client.api.MessageId)10 CompletableFuture (java.util.concurrent.CompletableFuture)9 Future (java.util.concurrent.Future)7 ConsumerImpl (org.apache.pulsar.client.impl.ConsumerImpl)7 Map (java.util.Map)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 ExecutorService (java.util.concurrent.ExecutorService)6 CryptoKeyReader (org.apache.pulsar.client.api.CryptoKeyReader)6 EncryptionKeyInfo (org.apache.pulsar.client.api.EncryptionKeyInfo)6 Field (java.lang.reflect.Field)5 ManagedLedgerImpl (org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl)5