(1)依赖
build.gradle
compile('org.springframework.kafka:spring-kafka')
(2)配置
application.properties
spring.kafka.bootstrap-servers=localhost:9093
spring.kafka.consumer.group-id=test
(3)生产者
@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;
@RequestMapping(value = "f1", method = RequestMethod.GET)
public void f1(@RequestParam(required = true) String data) {
kafkaTemplate.send("test", data);
}
@RequestMapping(value = "f2", method = RequestMethod.GET)
public void f2(@RequestParam(required = true) String data) {
kafkaTemplate.send("test", data).addCallback(new SuccessCallback<SendResult<String, Object>>() {
@Override
public void onSuccess(SendResult<String, Object> result) {
String topic = result.getRecordMetadata().topic();
int partition = result.getRecordMetadata().partition();
long offset = result.getRecordMetadata().offset();
log.info("{}:{}:{}", topic, partition, offset);
}
}, new FailureCallback() {
@Override
public void onFailure(Throwable ex) {
log.error("{}", ex.getMessage());
}
});
}
@RequestMapping(value = "f3", method = RequestMethod.GET)
public void f3(@RequestParam(required = true) String data) {
kafkaTemplate.send("test", data).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
@Override
public void onSuccess(SendResult<String, Object> result) {
String topic = result.getRecordMetadata().topic();
int partition = result.getRecordMetadata().partition();
long offset = result.getRecordMetadata().offset();
log.info("{}:{}:{}", topic, partition, offset);
}
@Override
public void onFailure(Throwable ex) {
log.error("{}", ex.getMessage());
}
});
}
(4)消费者
@KafkaListener(topics = {"test"})
public void f4(ConsumerRecord<String, Object> record) {
log.info("{}:{}:{}:{}:{}:{}", record.topic(), record.partition(), record.key(), record.value(), record.offset(), record.timestamp());
}
(5)测试结果
2024-04-19 15:10:55 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO cn.hwd.controller.Test3Controller - test:0:null:hello:21:1713510655274
2024-04-19 15:10:59 [kafka-producer-network-thread | producer-1] INFO cn.hwd.controller.Test3Controller - test:0:22
2024-04-19 15:10:59 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO cn.hwd.controller.Test3Controller - test:0:null:hello:22:1713510659344
2024-04-19 15:11:04 [kafka-producer-network-thread | producer-1] INFO cn.hwd.controller.Test3Controller - test:0:23
2024-04-19 15:11:04 [org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] INFO cn.hwd.controller.Test3Controller - test:0:null:hello:23:1713510664393