Spring Boot中@KafkaListener使用${}动态指定topic

项目场景:

在Spring Kafka中,我们可以使用${}来引用Spring的属性配置。这样我们就可以在不同的环境中重新配置topic名称,而不需要修改代码。


解决方案:

在application.properties或application.yml中定义topic名称:

java 复制代码
# application.properties
kafka.topic=myTopic

然后在你的代码中使用${}来引用这个属性:

java 复制代码
@KafkaListener(topics = "${kafka.topic}")
public void listen(String message) {
    System.out.println("Received message in topic : " + message);
}

如果你使用的是多个topic,你可以使用;来分割多个topic名称:

java 复制代码
# application.properties
kafka.topics=topic1;topic2;topic3

然后在你的代码中使用${}来引用这个属性:

java 复制代码
@KafkaListener(topics = "${kafka.topics}")
public void listen(String message) {
    System.out.println("Received message in topic : " + message);
}
复制代码
相关推荐
陌殇殇3 小时前
SpringBoot整合SpringCache缓存
spring boot·redis·缓存
小林学习编程5 小时前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
ladymorgana6 小时前
【Spring boot】tomcat Jetty Undertow对比,以及应用场景
spring boot·tomcat·jetty
IT_10246 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
DCTANT7 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.7 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
喜欢敲代码的程序员9 小时前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:项目搭建(一)
spring boot·mysql·elementui·vue·mybatis
华子w90892585910 小时前
基于 SpringBoot+Vue.js+ElementUI 的 “花开富贵“ 花园管理系统设计与实现7000字论文
vue.js·spring boot·elementui
小时候的阳光10 小时前
SpringBoot3 spring.factories 自动配置功能不生效?
spring boot·spring·失效·factories·imports
大只鹅11 小时前
Springboot3整合ehcache3缓存--XML配置和编程式配置
spring boot·缓存