[英]Is it possible to use Micronaut Kafka consumer dynamically without pre-defining the @Topic("TopicName")
I Have the following code, i want to provide the "topicName" as paramater or read it dynamically from a property, is the possible我有以下代码,我想提供“topicName”作为参数或从属性中动态读取它,是可能的
@KafkaListener(offsetReset = OffsetReset.EARLIEST)
public class KafkaConsumer {
private final String topicName;
public KafkaConsumer(String topicName) {
this.topicName = topicName;
}
@Topic("topicName")
public void receive(@KafkaKey String day, String message) {
System.out.println("Got Message for the - " + day + " and Message is " + message);
}
}
You can do:你可以做:
@Topic("${myTopicFromProperties}")
It's a bit confusing because if the question to be combined with the OP's comment "i need to use a different topic name in every method call, such as getting the topic name from the user and then creating a listener" one might think of the following examples/scenarios based on the official doc :这有点令人困惑,因为如果要将问题与 OP 的评论结合起来“我需要在每个方法调用中使用不同的主题名称,例如从用户那里获取主题名称然后创建一个侦听器”,则可能会想到以下内容基于官方文档的示例/场景:
@Topic({"topic1", "topic2", "topic3}) //multiple topics, see "Specifying Topics" sub-section on the linked page
public void receive(
@KafkaKey String key,
String message,
long offset,
int partition,
String topic, // topic as a parameter
long timestamp
) {
System.out.println("Got message: " + message + " from topic: " + topic);
}
You can also use ConsumerRecord
and get all the necessary information from there:您还可以使用
ConsumerRecord
并从那里获取所有必要的信息:
// "Receiving a ConsumerRecord" sub-section on the linked page
@Topic({"topic1", "topic2", "topic3})
public void receive(ConsumerRecord<String, String> record) {
System.out.println("Got message: " + record.value() + " from topic: " + record.topic());
}
You should also be able to specify the topics through the property placeholders as found in another answer like @Topic({"${topic1}", "${topic2}", "${topic3}"})
.您还应该能够通过属性占位符指定主题,如
@Topic({"${topic1}", "${topic2}", "${topic3}"})
类的另一个答案。
PS The above examples assume that for each specified topic both the message key and the message body are deserialized to strings. PS 上面的例子假设对于每个指定的主题,消息键和消息体都被反序列化为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.