Kafka服务器
参考另一个文章
新建Spring boot application
File-New-Spring boot-Spring starter project
spring boot 启动类KafkaProduerConsumerApplication.java
package com.springboot.kafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KafkaProduerConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(KafkaProduerConsumerApplication.class, args);
}
}
一个Controller类 KafkaController
package com.springboot.kafka.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.kafka.service.Producer;
@RestController
@RequestMapping("/kafka")
public class KafkaController {
@Autowired
private Producer producer;
@PostMapping("/post")
public void sendMessage(@RequestParam("msg") String msg) {
producer.publishToTopic(msg);
}
}
两个service类,一个Kafka的message producer, 一个kafka的message consumer。
package com.springboot.kafka.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class Producer {
private static final String topic = "mytopic";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void publishToTopic(String message) {
System.out.println("publish to topic " + topic);
this.kafkaTemplate.send(topic, message);
}
}
package com.springboot.kafka.service;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class Consumer {
@KafkaListener(topics = "mytopic", groupId = "mygroup")
public void consumerFromTopic(String message) {
System.out.println(message);
}
}
配置application.yml, 主要是kafka的参数。
server:
port: 8666
spring:
kafka:
consumer:
bootstrap-servers: 192.168.1.105:9092
group-id: mygroup
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
producer:
bootstrap-servers: 192.168.1.105:9092
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
测试
启动192.168.1.105:9092的Kafka服务器
启动spring boot application.
用Postman发送post请求
URL: http://127.0.0.1:8666/kafka/post Param:msg = hello kafka
在console上打印msg信息。