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服务

相关推荐
用户35218024547519 小时前
🎆从 Prompt 到 Skill:让 Spring AI Agent 学会"装新技能"
人工智能·spring boot·ai编程
用户3521802454754 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
昵称为空C4 天前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
霸道流氓气质5 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖5 天前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
Flittly5 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
星落zx5 天前
Spring Boot 多模型集成:优雅调用全球主流大模型
人工智能·spring boot·chatgpt
一杯奶茶¥5 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
进阶的小名5 天前
Spring Boot SSE + Nginx 配置:解决 EventSource 不实时返回、连接超时、流式响应被缓冲问题
spring boot·后端·nginx