Search in sources :

Example 6 with ContainerProperties

use of org.springframework.kafka.listener.ContainerProperties in project spring-kafka by spring-projects.

the class ReplyingKafkaTemplateTests method createTemplate.

public ReplyingKafkaTemplate<Integer, String, String> createTemplate(TopicPartitionOffset topic) {
    ContainerProperties containerProperties = new ContainerProperties(topic);
    Map<String, Object> consumerProps = KafkaTestUtils.consumerProps(this.testName, "false", embeddedKafka);
    DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
    KafkaMessageListenerContainer<Integer, String> container = new KafkaMessageListenerContainer<>(cf, containerProperties);
    container.setBeanName(this.testName);
    ReplyingKafkaTemplate<Integer, String, String> template = new ReplyingKafkaTemplate<>(this.config.pf(), container);
    template.setSharedReplyTopic(true);
    template.start();
    assertThat(template.getAssignedReplyTopicPartitions()).hasSize(1);
    assertThat(template.getAssignedReplyTopicPartitions().iterator().next().topic()).isEqualTo(topic.getTopic());
    return template;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) DefaultKafkaConsumerFactory(org.springframework.kafka.core.DefaultKafkaConsumerFactory)

Example 7 with ContainerProperties

use of org.springframework.kafka.listener.ContainerProperties in project spring-kafka by spring-projects.

the class ReplyingKafkaTemplateTests method testAggregateOrphansNotStored.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testAggregateOrphansNotStored() throws Exception {
    GenericMessageListenerContainer container = mock(GenericMessageListenerContainer.class);
    ContainerProperties properties = new ContainerProperties("two");
    properties.setAckMode(AckMode.MANUAL);
    given(container.getContainerProperties()).willReturn(properties);
    ProducerFactory pf = mock(ProducerFactory.class);
    Producer producer = mock(Producer.class);
    given(pf.createProducer()).willReturn(producer);
    AtomicReference<byte[]> correlation = new AtomicReference<>();
    willAnswer(invocation -> {
        ProducerRecord rec = invocation.getArgument(0);
        correlation.set(rec.headers().lastHeader(KafkaHeaders.CORRELATION_ID).value());
        return new SettableListenableFuture<>();
    }).given(producer).send(any(), any());
    AggregatingReplyingKafkaTemplate template = new AggregatingReplyingKafkaTemplate(pf, container, (list, timeout) -> true);
    template.setDefaultReplyTimeout(Duration.ofSeconds(30));
    template.start();
    List<ConsumerRecord> records = new ArrayList<>();
    ConsumerRecord record = new ConsumerRecord("two", 0, 0L, null, "test1");
    RequestReplyFuture future = template.sendAndReceive(new ProducerRecord("one", null, "test"));
    record.headers().add(new RecordHeader(KafkaHeaders.CORRELATION_ID, correlation.get()));
    records.add(record);
    Consumer consumer = mock(Consumer.class);
    template.onMessage(records, consumer);
    assertThat(future.get(10, TimeUnit.SECONDS)).isNotNull();
    assertThat(KafkaTestUtils.getPropertyValue(template, "pending", Map.class)).hasSize(0);
    Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
    offsets.put(new TopicPartition("two", 0), new OffsetAndMetadata(1));
    verify(consumer).commitSync(offsets, Duration.ofSeconds(30));
    // simulate redelivery after completion
    template.onMessage(records, consumer);
    assertThat(KafkaTestUtils.getPropertyValue(template, "pending", Map.class)).hasSize(0);
    template.stop();
    template.destroy();
}
Also used : SettableListenableFuture(org.springframework.util.concurrent.SettableListenableFuture) HashMap(java.util.HashMap) DefaultKafkaProducerFactory(org.springframework.kafka.core.DefaultKafkaProducerFactory) ProducerFactory(org.springframework.kafka.core.ProducerFactory) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Producer(org.apache.kafka.clients.producer.Producer) Consumer(org.apache.kafka.clients.consumer.Consumer) TopicPartition(org.apache.kafka.common.TopicPartition) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) GenericMessageListenerContainer(org.springframework.kafka.listener.GenericMessageListenerContainer) RecordHeader(org.apache.kafka.common.header.internals.RecordHeader) Test(org.junit.jupiter.api.Test)

Example 8 with ContainerProperties

use of org.springframework.kafka.listener.ContainerProperties in project spring-kafka by spring-projects.

the class DefaultKafkaConsumerFactoryTests method testContainerTxProducerIsNotCached.

@SuppressWarnings("unchecked")
@Test
public void testContainerTxProducerIsNotCached() throws Exception {
    Map<String, Object> producerProps = KafkaTestUtils.producerProps(this.embeddedKafka);
    DefaultKafkaProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(producerProps);
    KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf);
    DefaultKafkaProducerFactory<Integer, String> pfTx = new DefaultKafkaProducerFactory<>(producerProps);
    pfTx.setTransactionIdPrefix("fooTx.");
    KafkaTemplate<Integer, String> templateTx = new KafkaTemplate<>(pfTx);
    Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("txCache2Group", "false", this.embeddedKafka);
    DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
    ContainerProperties containerProps = new ContainerProperties("txCache2");
    CountDownLatch latch = new CountDownLatch(1);
    containerProps.setMessageListener((MessageListener<Integer, String>) r -> {
        templateTx.send("txCacheSendFromListener", "bar");
        templateTx.send("txCacheSendFromListener", "baz");
        latch.countDown();
    });
    KafkaTransactionManager<Integer, String> tm = new KafkaTransactionManager<>(pfTx);
    containerProps.setTransactionManager(tm);
    KafkaMessageListenerContainer<Integer, String> container = new KafkaMessageListenerContainer<>(cf, containerProps);
    container.start();
    try {
        ListenableFuture<SendResult<Integer, String>> future = template.send("txCache2", "foo");
        future.get(10, TimeUnit.SECONDS);
        assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
        assertThat(KafkaTestUtils.getPropertyValue(pfTx, "cache", Map.class)).hasSize(0);
    } finally {
        container.stop();
        pf.destroy();
        pfTx.destroy();
    }
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) AopUtils(org.springframework.aop.support.AopUtils) ListenableFuture(org.springframework.util.concurrent.ListenableFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) EmbeddedKafkaBroker(org.springframework.kafka.test.EmbeddedKafkaBroker) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) SpringJUnitConfig(org.springframework.test.context.junit.jupiter.SpringJUnitConfig) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) BDDMockito.given(org.mockito.BDDMockito.given) KafkaTransactionManager(org.springframework.kafka.transaction.KafkaTransactionManager) Map(java.util.Map) Metric(org.apache.kafka.common.Metric) MetricName(org.apache.kafka.common.MetricName) Deserializer(org.apache.kafka.common.serialization.Deserializer) Consumer(org.apache.kafka.clients.consumer.Consumer) KafkaTestUtils(org.springframework.kafka.test.utils.KafkaTestUtils) Properties(java.util.Properties) EmbeddedKafka(org.springframework.kafka.test.context.EmbeddedKafka) Listener(org.springframework.kafka.core.ConsumerFactory.Listener) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) Collectors(java.util.stream.Collectors) MessageListener(org.springframework.kafka.listener.MessageListener) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractMap(java.util.AbstractMap) List(java.util.List) Stream(java.util.stream.Stream) SendResult(org.springframework.kafka.support.SendResult) ProxyFactory(org.springframework.aop.framework.ProxyFactory) Collections(java.util.Collections) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) Mockito.mock(org.mockito.Mockito.mock) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) KafkaTransactionManager(org.springframework.kafka.transaction.KafkaTransactionManager) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) CountDownLatch(java.util.concurrent.CountDownLatch) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) SendResult(org.springframework.kafka.support.SendResult) Test(org.junit.jupiter.api.Test)

Example 9 with ContainerProperties

use of org.springframework.kafka.listener.ContainerProperties in project spring-cloud-contract by spring-cloud.

the class StubRunnerKafkaConfiguration method registerContainers.

private void registerContainers(ConfigurableListableBeanFactory beanFactory, List<Contract> matchingContracts, String flowName, StubRunnerKafkaRouter listener) {
    // listener's container
    ConsumerFactory consumerFactory = beanFactory.getBean(ConsumerFactory.class);
    for (Contract matchingContract : matchingContracts) {
        if (matchingContract.getInput() == null) {
            continue;
        }
        String destination = MapConverter.getStubSideValuesForNonBody(matchingContract.getInput().getMessageFrom()).toString();
        ContainerProperties containerProperties = new ContainerProperties(destination);
        KafkaMessageListenerContainer container = listenerContainer(consumerFactory, containerProperties, listener);
        String containerName = flowName + ".container";
        Object initializedContainer = beanFactory.initializeBean(container, containerName);
        beanFactory.registerSingleton(containerName, initializedContainer);
        if (log.isDebugEnabled()) {
            log.debug("Initialized kafka message container with name [" + containerName + "] listening to destination [" + destination + "]");
        }
    }
}
Also used : ConsumerFactory(org.springframework.kafka.core.ConsumerFactory) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) Contract(org.springframework.cloud.contract.spec.Contract)

Example 10 with ContainerProperties

use of org.springframework.kafka.listener.ContainerProperties in project vividus by vividus-framework.

the class KafkaSteps method startKafkaListener.

/**
 * Starts the Kafka consumer with the provided configuration to listen the specified topics. The consumer must be
 * stopped when it's not needed.
 *
 * @param consumerKey The key of the producer configuration
 * @param topics      The comma-separated set of topics to listen
 */
@When("I start consuming messages from `$consumerKey` Kafka topics `$topics`")
public void startKafkaListener(String consumerKey, Set<String> topics) {
    stopListener(getListeners().remove(consumerKey), false);
    BlockingQueue<String> messageQueue = new LinkedBlockingDeque<>();
    testContext.get(MESSAGES_KEY, HashMap::new).put(consumerKey, messageQueue);
    ContainerProperties containerProperties = new ContainerProperties(topics.toArray(new String[0]));
    containerProperties.setMessageListener((MessageListener<String, String>) data -> messageQueue.add(data.value()));
    GenericMessageListenerContainer<String, String> container = new KafkaMessageListenerContainer<>(consumerFactories.get(consumerKey), containerProperties);
    container.start();
    getListeners().put(consumerKey, container);
    LOGGER.info("Kafka message listener is started");
}
Also used : GenericMessageListenerContainer(org.springframework.kafka.listener.GenericMessageListenerContainer) VariableContext(org.vividus.context.VariableContext) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) Collectors.collectingAndThen(java.util.stream.Collectors.collectingAndThen) Function(java.util.function.Function) ArrayList(java.util.ArrayList) When(org.jbehave.core.annotations.When) DefaultKafkaProducerFactory(org.springframework.kafka.core.DefaultKafkaProducerFactory) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) StringDeserializer(org.apache.kafka.common.serialization.StringDeserializer) KafkaTemplate(org.springframework.kafka.core.KafkaTemplate) DurationBasedWaiter(org.vividus.util.wait.DurationBasedWaiter) VariableScope(org.vividus.variable.VariableScope) Collectors.mapping(java.util.stream.Collectors.mapping) Duration(java.time.Duration) Map(java.util.Map) ComparisonRule(org.vividus.steps.ComparisonRule) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) Map.entry(java.util.Map.entry) StringUtils.substringAfter(org.apache.commons.lang3.StringUtils.substringAfter) ProducerConfig(org.apache.kafka.clients.producer.ProducerConfig) IPropertyParser(org.vividus.util.property.IPropertyParser) Logger(org.slf4j.Logger) DefaultKafkaConsumerFactory(org.springframework.kafka.core.DefaultKafkaConsumerFactory) AfterStory(org.jbehave.core.annotations.AfterStory) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) Collectors(java.util.stream.Collectors) MessageListener(org.springframework.kafka.listener.MessageListener) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Matcher(org.hamcrest.Matcher) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) SoftAssert(org.vividus.softassert.SoftAssert) StringUtils.substringBefore(org.apache.commons.lang3.StringUtils.substringBefore) TestContext(org.vividus.testcontext.TestContext) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ContainerProperties(org.springframework.kafka.listener.ContainerProperties) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) When(org.jbehave.core.annotations.When)

Aggregations

ContainerProperties (org.springframework.kafka.listener.ContainerProperties)73 KafkaMessageListenerContainer (org.springframework.kafka.listener.KafkaMessageListenerContainer)46 DefaultKafkaConsumerFactory (org.springframework.kafka.core.DefaultKafkaConsumerFactory)41 Test (org.junit.jupiter.api.Test)38 DefaultKafkaProducerFactory (org.springframework.kafka.core.DefaultKafkaProducerFactory)30 KafkaTemplate (org.springframework.kafka.core.KafkaTemplate)26 QueueChannel (org.springframework.integration.channel.QueueChannel)21 ErrorMessage (org.springframework.messaging.support.ErrorMessage)19 Message (org.springframework.messaging.Message)18 MessageHeaders (org.springframework.messaging.MessageHeaders)18 CountDownLatch (java.util.concurrent.CountDownLatch)17 DirectChannel (org.springframework.integration.channel.DirectChannel)17 MessageChannel (org.springframework.messaging.MessageChannel)14 Acknowledgment (org.springframework.kafka.support.Acknowledgment)11 Type (java.lang.reflect.Type)10 HashMap (java.util.HashMap)9 StringDeserializer (org.apache.kafka.common.serialization.StringDeserializer)9 BeanFactory (org.springframework.beans.factory.BeanFactory)9 Bean (org.springframework.context.annotation.Bean)9 ConcurrentMessageListenerContainer (org.springframework.kafka.listener.ConcurrentMessageListenerContainer)9