Search in sources :

Example 1 with PulsarKafkaSchema

use of org.apache.pulsar.client.kafka.compat.PulsarKafkaSchema in project pulsar-adapters by apache.

the class KafkaApiTest method testProducerConsumerMixedSchemaWithPulsarKafkaClient.

@Test
public void testProducerConsumerMixedSchemaWithPulsarKafkaClient() throws Exception {
    String topic = "testProducerConsumerMixedSchemaWithPulsarKafkaClient";
    Schema<String> keySchema = new PulsarKafkaSchema<>(new StringSerializer(), new StringDeserializer());
    JSONSchema<Foo> valueSchema = JSONSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).build());
    Properties props = new Properties();
    props.put("bootstrap.servers", getPlainTextServiceUrl());
    props.put("group.id", "my-subscription-name");
    props.put("enable.auto.commit", "false");
    props.put("key.serializer", IntegerSerializer.class.getName());
    props.put("value.serializer", StringSerializer.class.getName());
    props.put("key.deserializer", StringDeserializer.class.getName());
    props.put("value.deserializer", StringDeserializer.class.getName());
    @Cleanup Consumer<String, Foo> consumer = new KafkaConsumer<>(props, keySchema, valueSchema);
    consumer.subscribe(Arrays.asList(topic));
    Producer<String, Foo> producer = new KafkaProducer<>(props, keySchema, valueSchema);
    for (int i = 0; i < 10; i++) {
        Foo foo = new Foo();
        foo.setField1("field1");
        foo.setField2("field2");
        foo.setField3(i);
        producer.send(new ProducerRecord<>(topic, "hello" + i, foo));
    }
    producer.flush();
    producer.close();
    AtomicInteger received = new AtomicInteger();
    while (received.get() < 10) {
        ConsumerRecords<String, Foo> records = consumer.poll(100);
        if (!records.isEmpty()) {
            records.forEach(record -> {
                String key = record.key();
                Assert.assertEquals(key, "hello" + received.get());
                Foo value = record.value();
                Assert.assertEquals(value.getField1(), "field1");
                Assert.assertEquals(value.getField2(), "field2");
                Assert.assertEquals(value.getField3(), received.get());
                received.incrementAndGet();
            });
            consumer.commitSync();
        }
    }
}
Also used : KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) PulsarKafkaSchema(org.apache.pulsar.client.kafka.compat.PulsarKafkaSchema) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) ToString(lombok.ToString) Properties(java.util.Properties) IntegerSerializer(org.apache.kafka.common.serialization.IntegerSerializer) Cleanup(lombok.Cleanup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) Test(org.testng.annotations.Test)

Example 2 with PulsarKafkaSchema

use of org.apache.pulsar.client.kafka.compat.PulsarKafkaSchema in project pulsar-adapters by apache.

the class PulsarKafkaConsumer method poll.

@Override
public ConsumerRecords<K, V> poll(long timeoutMillis) {
    try {
        QueueItem item = receivedMessages.poll(timeoutMillis, TimeUnit.MILLISECONDS);
        if (item == null) {
            return (ConsumerRecords<K, V>) ConsumerRecords.EMPTY;
        }
        Map<TopicPartition, List<ConsumerRecord<K, V>>> records = new HashMap<>();
        int numberOfRecords = 0;
        while (item != null) {
            TopicName topicName = TopicName.get(item.consumer.getTopic());
            String topic = topicName.getPartitionedTopicName();
            int partition = topicName.isPartitioned() ? topicName.getPartitionIndex() : 0;
            Message<byte[]> msg = item.message;
            MessageIdImpl msgId = (MessageIdImpl) msg.getMessageId();
            long offset = MessageIdUtils.getOffset(msgId);
            TopicPartition tp = new TopicPartition(topic, partition);
            if (lastReceivedOffset.get(tp) == null && !unpolledPartitions.contains(tp)) {
                log.info("When polling offsets, invalid offsets were detected. Resetting topic partition {}", tp);
                resetOffsets(tp);
            }
            K key = getKey(topic, msg);
            if (valueSchema instanceof PulsarKafkaSchema) {
                ((PulsarKafkaSchema<V>) valueSchema).setTopic(topic);
            }
            V value = valueSchema.decode(msg.getData());
            ConsumerRecord<K, V> consumerRecord = new ConsumerRecord<>(topic, partition, offset, key, value);
            records.computeIfAbsent(tp, k -> new ArrayList<>()).add(consumerRecord);
            // Update last offset seen by application
            lastReceivedOffset.put(tp, offset);
            unpolledPartitions.remove(tp);
            if (++numberOfRecords >= maxRecordsInSinglePoll) {
                break;
            }
            // Check if we have an item already available
            item = receivedMessages.poll(0, TimeUnit.MILLISECONDS);
        }
        if (isAutoCommit && !records.isEmpty()) {
            // Commit the offset of previously dequeued messages
            commitAsync();
        }
        return new ConsumerRecords<>(records);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : TopicName(org.apache.pulsar.common.naming.TopicName) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ConsumerBuilder(org.apache.pulsar.client.api.ConsumerBuilder) PulsarConsumerKafkaConfig(org.apache.pulsar.client.kafka.compat.PulsarConsumerKafkaConfig) Message(org.apache.pulsar.client.api.Message) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) PulsarClientKafkaConfig(org.apache.pulsar.client.kafka.compat.PulsarClientKafkaConfig) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) ConsumerName(org.apache.pulsar.client.util.ConsumerName) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) InterfaceStability(org.apache.kafka.common.annotation.InterfaceStability) Map(java.util.Map) Metric(org.apache.kafka.common.Metric) MetricName(org.apache.kafka.common.MetricName) Deserializer(org.apache.kafka.common.serialization.Deserializer) PulsarClient(org.apache.pulsar.client.api.PulsarClient) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) TopicPartition(org.apache.kafka.common.TopicPartition) Properties(java.util.Properties) MessageIdUtils(org.apache.pulsar.client.util.MessageIdUtils) MessageListener(org.apache.pulsar.client.api.MessageListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) PartitionInfo(org.apache.kafka.common.PartitionInfo) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Collectors(java.util.stream.Collectors) Schema(org.apache.pulsar.client.api.Schema) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Base64(java.util.Base64) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageId(org.apache.pulsar.client.api.MessageId) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) PulsarKafkaSchema(org.apache.pulsar.client.kafka.compat.PulsarKafkaSchema) Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PulsarKafkaSchema(org.apache.pulsar.client.kafka.compat.PulsarKafkaSchema) ArrayList(java.util.ArrayList) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) TopicName(org.apache.pulsar.common.naming.TopicName) TopicPartition(org.apache.kafka.common.TopicPartition) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Properties (java.util.Properties)2 StringDeserializer (org.apache.kafka.common.serialization.StringDeserializer)2 PulsarKafkaSchema (org.apache.pulsar.client.kafka.compat.PulsarKafkaSchema)2 ArrayList (java.util.ArrayList)1 Base64 (java.util.Base64)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)1 BlockingQueue (java.util.concurrent.BlockingQueue)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeUnit (java.util.concurrent.TimeUnit)1 TimeoutException (java.util.concurrent.TimeoutException)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Pattern (java.util.regex.Pattern)1