Spring Boot - 获取spring.kafka客户端的application.properties中的主机名
问题描述:
我正在使用Spring-Kafka和Boot开发一个项目,并且希望获取属性spring.kafka的application.properties中的主机名。 consumer.client-Id,这样,如果出现问题,我的每个消费者都可以在服务器端日志中进行区分。Spring Boot - 获取spring.kafka客户端的application.properties中的主机名
有没有办法我能做到这一点?我检查了spring引用参考指南和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();
}
}
}
在这种情况下,我做到了,在启动应用程序本身,但它可以在任何豆来完成。
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
...
application.properties:
spring.kafka.consumer.client-id=foo
spring.kafka.consumer.group-id=myGroup
spring.kafka.consumer.auto-offset-reset=earliest
正如你所看到的,client-id
被覆盖。