spring整合kafka

原文链接:spring整合kafka_spring集成kafka-CSDN博客

1、导入依赖

复制代码
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>2.5.10.RELEASE</version>
</dependency>

2、yml配置

复制代码
spring: 
    kafka:
        bootstrap-servers: localhost:9092    # kafka连接接地址
        consumer:
              group-id: test-consumer-group    # 消费者所属消息组
              enable-auto-commit: true    #设置自动提交
              auto-commit-interval: 3000    #自动提交的间隔时间

3、测试

-生产者

复制代码
@Component
class KafkaProduce{
    @Autowired
    private KafkaTemplate kafkaTemplate;

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

-消费者

复制代码
@Component
class kafkaConsumer{
    @KafkaListener(topics = {"test"})
    public void handleMessage(ConsumerRecord record){
        System.out.println(record.value());
    }
}

-测试方法

复制代码
    @Autowired
    private KafkaProduce kafkaProduce;
    @Test
    void TestKafka(){
        kafkaProduce.sendMessage("test", "nihao");
        kafkaProduce.sendMessage("test", "nihaoma");

        try {
            sleep(1000 * 20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

也可以使用offset Explorer 2.3.2进行测试,使用方法见我的这篇博文:

offset explore 工具介绍(原kafka tool)_offset explorer-CSDN博客

相关推荐
阿维的博客日记1 天前
MultipartFile 是不是表示仅仅是一个分片?
java·后端·spring·multipartfile
一路向北North1 天前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务
weixin_727535621 天前
Spring @Transactional 事务失效:原理层面深度解析
java·spring
没钥匙的锁11 天前
16-Java反射机制:Spring IOC背后的核心技术
java·开发语言·spring
春卷同学1 天前
HarmonyOS掌上记账APP开发实践第23篇:弹性动效与手势 — EdgeEffect.Spring 与手势系统实战
spring·华为·harmonyos
大不点wow1 天前
Spring 中 @Bean、@Component 与 @Configuration 的作用及底层逻辑
java·spring
富士康质检员张全蛋1 天前
Kafka的操作 生产消息
分布式·kafka
大不点wow1 天前
为什么 Spring 更推荐构造器注入,而不是字段 `@Autowired`
java·spring·intellij-idea
卓怡学长2 天前
w255基于springboot仓库管理系统
java·数据库·spring boot·spring·intellij-idea
csdn2015_2 天前
springboot读取配置的方法
java·spring boot·spring