如何在Spring Boot中调用两个使用相同主题的Kafka监听器?

huangapple 未分类评论45阅读模式
英文:

How to call both Kafkalistener with same Topic in spring boot?

问题

我想使用相同的主题配置调用两种不同的方法。

假设我有一个消费者项目,其中有两个不同的类,这两个类有相同的kafkalistener方法。

方法1,类A:

@KafkaListener(topics = "vijay", groupId = "group_id")
public void consumeMethodOne(String jsonString) {
    System.out.println("ConsumerPrice1-->" + jsonString);
}

方法2,类B:

@KafkaListener(topics = "vijay", groupId = "group_id")
public void consumeMethodTwo(String jsonString) {
    System.out.println("ConsumerPrice1-->" + jsonString);
}

还有我的生产者:

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;

public void send(String value) {
    kafkaTemplate.send("vijay", "This is testing producer");
}

当我运行这个程序时,只有一个方法会执行。如果我想要执行这两个方法,因为它们都有相同的主题,那么我该如何设置?

英文:

I want to call two different methods with same Topic configuration.

Suppose I have Consumer project which have two different classes with same methods of kafkalistener .

Method 1 with class A :

@KafkaListener(topics = &quot;vijay&quot;, groupId = &quot;group_id&quot;)
	public void consumeMethodOne(String jsonString) {
		System.out.println(&quot;ConsumerPrice1--&gt;&quot;+jsonString);
	}

Method 2 with class B :

@KafkaListener(topics = &quot;vijay&quot;, groupId = &quot;group_id&quot;)
	public void consumeMethodTwo(String jsonString) {
		System.out.println(&quot;ConsumerPrice1--&gt;&quot;+jsonString);
	}

And my producer :

@Autowired
	private KafkaTemplate&lt;String, String&gt; kafkaTemplate;
	public void send(String value) {
		kafkaTemplate.send(&quot;vijay&quot;, &quot;This is testing producer&quot;);
	}

When I ran this program only one method executes so If I want to executes both methods because both have same topics so How could I do with setting?

答案1

得分: 0

消费者组是负载均衡主题的消费者的一种方式。如果您在同一组中有两个消费者(在您的情况下是"group_id"),只有其中一个会一次消费一条消息。通常,这会像消费者的应用程序ID,并用于扩展消费者。

但是,如果您想要两个消费者都消费相同的消息,您可以通过为它们分配两个不同的组ID来实现这一点。

@KafkaListener(topics = "vijay", groupId = "group_id2")
public void consumeMethodTwo(String jsonString) {
    System.out.println("ConsumerPrice1-->" + jsonString);
}
英文:

Consumer groups are a way of load balancing the consumers of a topic. If you have two consumers in the same group (in your case "group_id") only one of them will consume a message at a time.
Typically this would be like an application id of the consumer, and used to scale the consumer.

However, if you want two consumers and both to consume the same message you can do this by giving them two different group Id's.

@KafkaListener(topics = &quot;vijay&quot;, groupId = &quot;group_id2&quot;)
    public void consumeMethodTwo(String jsonString) {
        System.out.println(&quot;ConsumerPrice1--&gt;&quot;+jsonString);
    }

huangapple
  • 本文由 发表于 2020年5月19日 21:09:36
  • 转载请务必保留本文链接:https://java.coder-hub.com/61891857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定