org.springframework.kafka spring-kafka /*可以注释掉,利用父版本所声明的版本即可*/3.0.0
在application.propertities中配置
# KafkaProperties
# 配置服务,消费者:消费者的分组ID:在consumer的配置文件里有
# 是否自动提交消费者的偏移量。消费者读取消息时按偏移量读取,一般是移动提交
# 自动提交的频率,多长时间提交一次:3000ms
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=community-consumer-group
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=3000
利用方法,监听主题,一旦主题上有消息,就会调用方法去处理消息。会把消息包装成record,对record做出处理
package com.nowcoder.community;import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class KafkaTests {@Autowiredprivate KafkaProducer kafkaProducer;@Testpublic void testKafka() {//用生产者发送消息,然后用消费者处理消息(这里是打印)kafkaProducer.sendMessage("test", "你好");kafkaProducer.sendMessage("test", "在吗");//发完消息后,不能立刻结束,否则就看不到消费者的输出,//生产者是主动的,消费者是被动的,可能会有一点延迟try {Thread.sleep(1000 * 10);//1000ms*10} catch (InterruptedException e) {e.printStackTrace();}}}@Component
class KafkaProducer {//一般会将生产者或消费者的代码封装,希望用spring的容器来管理@Autowiredprivate KafkaTemplate kafkaTemplate;//被spring整合的kafka工具public void sendMessage(String topic, String content) {//传入消息的主题,消息的内容kafkaTemplate.send(topic, content);}}@Component
class KafkaConsumer {//封装消费者的bean//指定要监听的主题,不需要依赖template,服务启动了后,spring就会自动监听//消费者就会有一个线程阻塞,试图读取test主题的消息,若有消息,就会读取,若没有,就会阻塞@KafkaListener(topics = {"test"})public void handleMessage(ConsumerRecord record) {//处理一个消息System.out.println(record.value());//读取消息}}
上一篇:二分查找详解