Spring Boot-在应用程序.Properties中获取Spring的主机名-Kafka客户端ID [英] Spring Boot - Getting the hostname in application.properties for Spring-Kafka client Id
本文介绍了Spring Boot-在应用程序.Properties中获取Spring的主机名-Kafka客户端ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Spring-Kafka和Boot进行一个项目,我想在应用程序中获取spring.kafka.Consumer er.Client-ID属性的主机名,以便在服务器端日志中区分我的每个消费者,如果出现问题。
我有办法做到这一点吗?我查看了Spring Boot参考指南和java.lang.System类,但没有找到有用的指针。
推荐答案
有一种方法--将EnvironmentAware
Bean添加到您的配置中...
@SpringBootApplication
public class So43191948Application implements EnvironmentAware {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So43191948Application.class, args);
@SuppressWarnings("unchecked")
KafkaTemplate<String, String> template = context.getBean(KafkaTemplate.class);
template.send("so43191948", "foo");
Thread.sleep(10000);
context.close();
}
@KafkaListener(topics = "so43191948")
public void foo(String in) {
System.out.println(in);
}
@Override
public void setEnvironment(Environment environment) {
Properties props = new Properties();
try {
props.setProperty("spring.kafka.consumer.client-id", InetAddress.getLocalHost().getHostName() + ".client");
PropertiesPropertySource propertySource = new PropertiesPropertySource("myProps", props);
if (environment instanceof StandardEnvironment) {
((StandardEnvironment) environment).getPropertySources().addFirst(propertySource);
}
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
在本例中,我是在引导应用程序本身中完成的,但它可以在任何Bean中完成。
2017-04-03 16:12:32.646 INFO 64879 --- [ main] o.a.k.clients.consumer.ConsumerConfig
: ConsumerConfig values:
auto.commit.interval.ms = 5000
auto.offset.reset = earliest
bootstrap.servers = [localhost:9092]
check.crcs = true
client.id = myhost.client
...
应用程序.属性:
spring.kafka.consumer.client-id=foo
spring.kafka.consumer.group-id=myGroup
spring.kafka.consumer.auto-offset-reset=earliest
如您所见,client-id
已被覆盖。
这篇关于Spring Boot-在应用程序.Properties中获取Spring的主机名-Kafka客户端ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文