Spring 引导 - 在 application.properties 中获取 Spring-Kafka 客户端 ID 的主机名

Spring Boot - Getting the hostname in application.properties for Spring-Kafka client Id

我正在使用 Spring-Kafka 和 Boot 开发一个项目,我想在 application.properties 中获取 属性 spring.kafka.consumer.client-Id 的主机名,所以如果出现问题,可以在服务器端日志中区分我的每个消费者。

有什么办法可以做到吗?我查看了 spring 引导参考指南和 java.lang.System class 但找不到有用的指示。

这是一种方法 - 在您的配置中添加一个 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
...

application.properties:

spring.kafka.consumer.client-id=foo
spring.kafka.consumer.group-id=myGroup
spring.kafka.consumer.auto-offset-reset=earliest

如您所见,client-id 已被覆盖。

import java.net.InetAddress;
import java.net.UnknownHostException;  

private String getHostAddress() {
String hostaddress = "";
try {
  hostaddress =  InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
  log.error("Error while fetching hostaddress:", e);
}
return hostaddress;}