本文主要是介绍5.9spring整合卡夫卡,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
配置卡夫卡,在 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 {@Autowiredprivate KafkaProducer kafkaProducer;@Testpublic void testKafka() {kafkaProducer.sendMessage("test", "你好");kafkaProducer.sendMessage("test", "在吗");try {Thread.sleep(1000 * 10);//阻塞} catch (InterruptedException e) {e.printStackTrace();}}}
其中:
Component//表明这个bean由spring容器管理
class KafkaProducer {//生产者bean@Autowiredprivate 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}
输出:
表明消费者成功消费这个消息
这篇关于5.9spring整合卡夫卡的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!