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 {
 @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


}

输出:
在这里插入图片描述
表明消费者成功消费这个消息

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值