1、添加依赖
<!-- kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
注意:Kafka安装的版本为kafka_2.12-0.11.0.1,所以引入的kafka依赖需要1.3以上版本,这样kafka client才是0.11.0.0的
2、Kafka配置
#kafka
spring.kafka.bootstrap-servers=192.168.xx.xx:9092
spring.kafka.consumer.group-id=pvs
#key-value序列化反序列化
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.batch-size=65536
spring.kafka.producer.buffer-memory=524288
3、使用例子
@Controller
@EnableAutoConfiguration
public class SampleController {
private Logger logger = LoggerFactory.getLogger(SampleController.class);
@Autowired
private KafkaTemplate<String, String> template;
@RequestMapping("/send")
@ResponseBody
String send(String topic, String key, String data) {
template.send(topic, key, data);
return "success";
}
@KafkaListener(id = "t1", topics = {"t1"})
public void listenT1(ConsumerRecord<?, ?> cr) throws Exception {
logger.info("{} - {} : {}", cr.topic(), cr.key(), cr.value());
}
@KafkaListener(id = "t2", topics = {"t2"})
public void listenT2(ConsumerRecord<?, ?> cr) throws Exception {
logger.info("{} - {} : {}", cr.topic(), cr.key(), cr.value());
}
浏览器调用:http://localhost:8080/send?topic=t2&key=test1&data=hello122
后台: