配置卡夫卡,在 application.Properties中
# KafkaProperties
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
测试代码:
新建KafkaTests
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 {
@Autowired
private KafkaProducer kafkaProducer;
@Test
public void testKafka() {
kafkaProducer.sendMessage("test", "你好");
kafkaProducer.sendMessage("test", "在吗");
try {
Thread.sleep(1000 * 10);//阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
其中:
Component//表明这个bean由spring容器管理
class KafkaProducer {//生产者bean
@Autowired
private KafkaTemplate kafkaTemplate;//生产者发送消息主要依靠kafkaTemplate工具,是在spring容器里,所以需要注入。
public void sendMessage(String topic, String content) {
kafkaTemplate.send(topic, content);
}//传入消息主题和内容,以发送
}
@Component
class KafkaConsumer {//消费者bean
@KafkaListener(topics = {"test"})//消费者 不需要依靠 kafkaTemplate,而需要用到注解,topics里面的参数是 要关注监听的主题
public void handleMessage(ConsumerRecord record) {
System.out.println(record.value());
}//将消息封装成record
}
输出:
表明消费者成功消费这个消息