依赖

可以用spring-kafka-1.1.8.RELEASE版本的

  1. <dependency>
  2. <groupId>org.springframework.kafka</groupId>
  3. <artifactId>spring-kafka</artifactId>
  4. </dependency>

Java代码

  1. public class Constant {
  2. public static final String TOPIC_STARTUP = "topic_startup";
  3. public static final String TOPIC_EVENT="topic_event";
  4. }
  1. @PostMapping("/log")
  2. public String logger(@RequestParam("log") String log) {
  3. //System.out.println(log);
  4. //写到kafka 先创建kafak生产者 再调生产者send方法
  5. sendToKafka(log);
  6. return "666";
  7. }
  8. @Autowired
  9. private KafkaTemplate template;
  10. private void sendToKafka(String log) {
  11. String topic = Constant.TOPIC_STARTUP;
  12. if (log.contains("event")) {
  13. topic = Constant.TOPIC_EVENT;
  14. }
  15. template.send(topic, log);
  16. }

application.properties配置文件

  1. #kafka的配置 想联系到kafka kafka集群地址 生产者序列化器 key-v
  2. spring.kafka.bootstrap-servers=zjj101:9092,zjj102:9092,zjj103:9092
  3. # key value的序列化器
  4. spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
  5. spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer

开始测试

这里面就能推送数据了
SpringBoot 将数据推到Kafka的Topic入门案例 - 图1