使用Spring EL将可选的后缀从属性添加到@KafkaListener中的consumerGroup
我有一个带有 Kafka Consumers 的简单 Spring Boot 应用程序,看起来像
@KafkaListener(topics="topic", groupId="SOME_CONSTANT") {
....
}
我需要做的是添加可选的 Spring Boot 属性(来自环境变量,但这并不重要)可以说: myapp.env: TEST
当该变量存在时,我应该自动将消费者组更新为 SOME_CONSTANT-TEST
我正在使用 SPEL
@KafkaListener(topics="topic", groupId="#{ '${myApp.env}' == null ? 'SOME_CONSTANT' : 'SOME_CONSTANT' + '-' + '${myApp.env}}'") {
....
}
但这似乎不起作用:/有什么想法吗?
I have simple spring boot application with Kafka Consumers that looks like
@KafkaListener(topics="topic", groupId="SOME_CONSTANT") {
....
}
What I am required to do Is to add optional spring boot property (from env variables but that is not important) lets say:myapp.env: TEST
And when that variable is present I should automatically update consumer group to beSOME_CONSTANT-TEST
I am playing with SPEL
@KafkaListener(topics="topic", groupId="#{ '${myApp.env}' == null ? 'SOME_CONSTANT' : 'SOME_CONSTANT' + '-' + '${myApp.env}}'") {
....
}
But that does not seem to work :/ Any Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
T
运算符读取常量的值,并在没有环境变量的情况下使用冒号 ':':@KafkaListener(topics="topic", groupId=" #{ '${my.app.env:}' == '' ? T(com.mypackage.MyListener).SOME_CONSTANT : T(com.mypackage.MyListener).SOME_CONSTANT + '-' + '${my.app.env:}'}")
这是使用此解决方案的示例应用程序:
输出:
2022-02-28 14:26:14.733 INFO 18841 --- [ntainer#0-0-C-1] 1291726$$EnhancerBySpringCGLIB$$cf264156 :收到消息我来自组 id my-group-id- 的消息常量
如果我添加
71291726.my.app.env = TEST
到application.properties
文件:2022-02-28 14:34:03.900 INFO 18870 --- [ntainer #0-0-C-1] 1291726$$EnhancerBySpringCGLIB$$e1a5933e:收到消息我的消息来自组 id my-group-id-constant-TEST
You can use the
T
operator to read the constant's value, and use the colon ':' for the case when there's no env variable:@KafkaListener(topics="topic", groupId="#{ '${my.app.env:}' == '' ? T(com.mypackage.MyListener).SOME_CONSTANT : T(com.mypackage.MyListener).SOME_CONSTANT + '-' + '${my.app.env:}'}")
Here's a sample application with this solution:
Output:
2022-02-28 14:26:14.733 INFO 18841 --- [ntainer#0-0-C-1] 1291726$$EnhancerBySpringCGLIB$$cf264156 : Received message My message from group id my-group-id-constant
If I add
71291726.my.app.env = TEST
to theapplication.properties
file:2022-02-28 14:34:03.900 INFO 18870 --- [ntainer#0-0-C-1] 1291726$$EnhancerBySpringCGLIB$$e1a5933e : Received message My message from group id my-group-id-constant-TEST