原文链接:spring整合kafka_spring集成kafka-CSDN博客
1、导入依赖
<dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId><version>2.5.10.RELEASE</version>
</dependency>
2、yml配置
spring: kafka:bootstrap-servers: localhost:9092 # kafka连接接地址consumer:group-id: test-consumer-group # 消费者所属消息组enable-auto-commit: true #设置自动提交auto-commit-interval: 3000 #自动提交的间隔时间
3、测试
-生产者
@Component
class KafkaProduce{@Autowiredprivate KafkaTemplate kafkaTemplate;public void sendMessage(String topic, String content){kafkaTemplate.send(topic, content);}
}
-消费者
@Component
class kafkaConsumer{@KafkaListener(topics = {"test"})public void handleMessage(ConsumerRecord record){System.out.println(record.value());}
}
-测试方法
@Autowiredprivate KafkaProduce kafkaProduce;@Testvoid TestKafka(){kafkaProduce.sendMessage("test", "nihao");kafkaProduce.sendMessage("test", "nihaoma");try {sleep(1000 * 20);} catch (InterruptedException e) {e.printStackTrace();}}
也可以使用offset Explorer 2.3.2进行测试,使用方法见我的这篇博文:
offset explore 工具介绍(原kafka tool)_offset explorer-CSDN博客