gpt4 book ai didi

java - kafka消息的多种实现(java泛型)

转载 作者:行者123 更新时间:2023-12-02 09:12:52 24 4
gpt4 key购买 nike

我正在尝试根据事件类型为 kafka 事件创建多个实现类。

public class KafkaListener {
@Autowired
Service service;

@KafkaListener(topics = ("mytopic"), containerFactory = "kafkaListenerContainerFactory")
public void consumeSource(Object event) {
service.process(event);
}
}

public interface Service<E> {
void process(E event);
}

public class ServiceImpl1 implements Service<Event1> {
void process(Event1 event1) {
// process
}
}

public class ServiceImpl2 implements Service<Event2> {
void process(Event2 event2) {
// process
}
}

//Event1 & Event2 are 2 POJO classes with different inputs

是否可以实现或者我应该创建多个监听器,每个监听器对应一种事件类型?

最佳答案

只要事件由 Kafka 反序列化,您就可以使用类级别 @KafkaListener 和方法级别 @KafkaHandler

参见the documentation .

When you use @KafkaListener at the class-level, you must specify @KafkaHandler at the method level. When messages are delivered, the converted message payload type is used to determine which method to call. The following example shows how to do so:

@KafkaListener(id = "multi", topics = "myTopic")
static class MultiListenerBean {

@KafkaHandler
public void listen(String foo) {
...
}

@KafkaHandler
public void listen(Integer bar) {
...
}

@KafkaHandler(isDefault = true`)
public void listenDefault(Object object) {
...
}

}

Starting with version 2.1.3, you can designate a @KafkaHandler method as the default method that is invoked if there is no match on other methods. At most, one method can be so designated. When using @KafkaHandler methods, the payload must have already been converted to the domain object (so the match can be performed). Use a custom deserializer, the JsonDeserializer, or the JsonMessageConverter with its TypePrecedence set to TYPE_ID. See Serialization, Deserialization, and Message Conversion for more information.

关于java - kafka消息的多种实现(java泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59256214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com