环境配置:
1.增加spring-kafka的配置
spring
kafka: # 指定kafka 代理地址,可以多个
bootstrap-servers: 10.253.96.128:9092
template: # 指定默认topic id
default-topic: producer
listener: # 指定listener 容器中的线程数,用于提高并发量
concurrency: 5
consumer:
group-id: myGroup # 指定默认消费者group id
client-id: 200
max-poll-records: 200
auto-offset-reset: earliest # 最早未被消费的offset
producer:
batch-size: 1000 # 每次批量发送消息的数量
retries: 3
client-id: 200
2.增加一个服务地址的配置 在创建topic的地方需要单独使用
kafka:
producer:
servers: 10.253.96.128:9092
开发说明:
1.调用生产者发送消息,创建topic,查询topic信息的相关api
1》引用消费者类:
@Autowired
private Producer producer;
2》如果没有创建topic,首先创建topic
createTopic(kafkaEntity kafkaEntity)
3》查看自己创建的topic信息
selectTopicInfo(String topic)
4》发送消息到kafka
发送不包含key的消息:
sendChannelMess(String topic, String message)
发送包含key的消息
sendChannelMess(String topic, String key, String message)
2 消费端消费消息
消费端需要调用者自己实现,通过监听自己的topic实现消息的消费
案例如下:
/**
* 有消息就读取,只读取消息value
*/
@KafkaListener(topics = {"test13"},groupId = "myGroup")
public void receiveMessage(String message){
//收到通道的消息之后执行秒杀操作
System.out.println(message);
}
/**
* 有消息就读取,批量读取消息value
*/
@KafkaListener(topics = "test12",groupId = "myGroup")
public void onMessage(List<String> crs) {
for(String str : crs){
System.out.println("test12:" + str);
}
}
/**
* 有消息就读取,读取消息topic,offset,key,value等信息
*/
@KafkaListener(topics = "cjkj",groupId = "myGroup")
public String listenT1(ConsumerRecord<?, ?> cr){
System.out.println("listenT1收到消息,topic:>>>" + cr.topic() + " offset:>>" + cr.offset()+ " key:>>" + cr.key() + " value:>>" + cr.value());
return "";
}