kafka实战<二>spring整合kafka

  1. 引入依赖(改pom)

引入spring的kafka依赖
因为springboot的父类版本有自动控制,
所以不需要指定版本。
2.7.1版本对应的是3.1版本的kafka,如果低于这个版本会出现错误,启动时找不到相应的类。

<!-- https://mvnrepository.com/artifact/org.springframework.kafka/spring-kafka -->
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
</dependency>
  1. 修改yml或者config文件
################## kafka的配置 #########################
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
  1. 写测试类

package com.fuzekun.demo1.utils;

import com.fuzekun.demo1.Demo1Application;
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.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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;

/**
 * @author: Zekun Fu
 * @date: 2023/1/14 10:40
 * @Description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Demo1Application.class)
public class KafkaTest {

    /*
    * 测试是否已经连接和配置成功了
    * 1. 封装生产者和消费者代码
    * 2. 生产者发送消息,生产者线程等待
    * 3.
    * */
    @Autowired
    KafkaProducer producer;
    @Autowired
    KafkaConsumer consumer;
    @Test
    public void testConenction() {
        producer.sendMSG("test", "你好");
        producer.sendMSG("test", "在吗");

        try {
            Thread.sleep(1000 * 5);        // 睡眠5s, 等待自动调用消费者线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// 不能写成内部类,否则会@component注解没有用了

@Component
class KafkaProducer {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    public void sendMSG(String topic, String content) {
        kafkaTemplate.send(topic, content);
    }
}

@Component
class KafkaConsumer {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @KafkaListener(topics = {"test"})
    public void handlerMsg(ConsumerRecord record) {
//        System.out.println("自动调用了");
        System.out.println(record.value());
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值