springboot集成kafka

1、引入依赖

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

2、配置

bash 复制代码
server:
  port: 9099
spring:
  kafka:
    bootstrap-servers: 192.168.157.101:9092
    consumer:
      group-id: test-consumer-group
      max-poll-records: 10
      concurrency: 10
      #Kafka中没有初始偏移或如果当前偏移在服务器上不再存在时,默认区最新 ,有三个选项 【latest, earliest, none】
      auto-offset-reset: earliest
      #是否开启自动提交
      enable-auto-commit: false
      ack-mode: MANUAL_IMMEDIATE
      #自动提交的时间间隔
      auto-commit-interval: 1000
      #key的解码方式
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      #value的解码方式
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      properties:
        batch-listener: true

    producer:
      batch-size: 4096
      buffer-memory: 40960
      retries: 1
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
    listener:
      #创建多少个consumer,值必须小于等于Kafk Topic的分区数。
      ack-mode: MANUAL_IMMEDIATE
      concurrency: 1  #推荐设置为topic的分区数

3、测试

java 复制代码
    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;
    @Test
    void contextLoads() {
        for (int i = 0; i < 100; i++) {
            kafkaTemplate.send("hello","hello"+i);
        }

    }

如日志打印:Connection to node 0 (/127.0.0.1:9092)

bash 复制代码
#进入kafka安装目录
/usr/local/kafka_2.12-3.5.1/config
#编辑配置文件
vim server.properties
    
# 允许外部端口连接                                            
listeners=PLAINTEXT://0.0.0.0:9092  
# 外部代理地址                                                
advertised.listeners=PLAINTEXT://192.168.157.101:9092  

重启kafka服务

相关推荐
学长毕设21 小时前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
Java内核笔记1 天前
方法级 trace 看不出第几轮:给 Agent 补一层轮次维度
人工智能·spring boot·后端
她的男孩1 天前
转办给同事后对方一点同意就报幂等冲突:Forge Admin 不把转办键当成终态
spring boot·低代码·工作流引擎
北风toto1 天前
Spring Boot 常用注解 · 概要笔记
spring boot·笔记·后端
宋冠巡1 天前
Spring Boot 4 + OpenTelemetry + Spring Cloud Gateway:全链路 TraceId 传播验证
spring boot·可观测性·traceid
下一站春风里1 天前
Spring IoC 控制反转 完整技术笔记
java·spring boot·笔记·spring
小码哥0681 天前
Spring Boot在线租房系统源码:UniApp找房、VR展示与预约管理落地解析
spring boot·租房小程序·租房系统·在线租房
芜名氏1 天前
API 文档生成工具——SpringDoc
java·spring boot·ci/cd·设计规范
乌暮2 天前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
小荷才露尖尖角,早有蜻蜓立上头2 天前
SpringBoot+QQ邮箱发送邮件
spring boot