【Java Web】Spring整合Kafka

  • 引入依赖
    • spring-kafka
  • 配置Kafka
    • 配置server/consumer
  • 访问Kafka
    • 生产者
      • kafkaTemplate.send(topic,data)
    • 消费者
      • @KafkaListenner(topics={"test"})
      • public void handleMessage(ConsumerRecord record) { }

application.properties配置:

java 复制代码
# 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

测试代码:

java 复制代码
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) {
            throw new RuntimeException(e);
        }
    }
}

@Component
class KafkaProducer{

    @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());
    }
}
相关推荐
JavaGuide11 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang021712 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户693717500138412 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk816312 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen12 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus12 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing13 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真13 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup13 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法14 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端