前言 :
- 启动zk
- 启动kafka
- kafka中创建一个主题topic
引入依赖:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
Java 代码
1.创建一个生产者类Produce,这里未来方便测试使用前端传入参数的信息生产数据
/**
* @author honor
*/
@RestController
@RequestMapping("/kafka")
public class KafkaProducerController {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@RequestMapping("/send")
public String send(String message){
//使用kafka模板发送信息
kafkaTemplate.send("test", message);
return "success";
}
}
- 创建一个消费类KafkaConsumer,并监听某个topic
/**
* @author honor
*/
@Component
public class KafkaConsumer {
@KafkaListener(topics = "test")
public void listen (ConsumerRecord<?, ?> record) throws Exception {
System.out.printf("topic = %s, offset = %d, value = %s \n", record.topic(), record.offset(), record.value());
}
}
测试:
自此简单整合结束