I'm using two microservices in order to communicate with each other using Kafka. On one microservice there is the listener, and on the other microservice, the sender. The problem is that whenever producer sends a message, consumer will get 20 duplicate messages, and i want the consumer to receive only one.
Microservice A:
@Service
public class LocationProducer {
private static final String MAINLOCATION = "mainlocation";
@Autowired
private KafkaTemplate<String,String> kafkaTemplate;
public void sendMessage(String message){
this.kafkaTemplate.send(MAINLOCATION,message);
}
kafka:
producer:
bootstrap-servers: localhost:9092
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
Microservice B:
@Service
public class LocationConsumer {
@Autowired
LocationService locationService;
@KafkaListener(topics = "mainlocation", groupId = "group_id")
public void consume(String location){
locationService.saveLocation(new Location(1,location));
}
kafka:
consumer:
bootstrap-servers: localhost:9092
group-id: group_id
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
Docker compose code:
zookeeper:
image: wurstmeister/zookeeper
ports:
- "2181:2181"
kafka:
image: wurstmeister/kafka
ports:
- "9092:9092"
environment:
KAFKA_ADVERTISED_HOST_NAME: localhost
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_CREATE_TOPIC: "mainlocation:1:3"
Aditional information:
When doing a debug in intelij, if i put a breakpoint on:
this.kafkaTemplate.send(MAINLOCATION,message);
This method will be executed twice
On the consumer side, after it receives the message it tries to save into a mongoDB and it fails with an exception ( might be relevant for this i don't know )
I even tried setting autocommit to true, configured max.poll seconds and the problem is the same.