Spring Boot - 获取Spring.Kafka客户端Id的application.properties中的主机名

时间:2017-04-03 18:35:28

标签: spring-boot spring-kafka

我正在使用Spring-Kafka和Boot开发一个项目,并希望在application.properties中获取属性spring.kafka.consumer.client-Id的主机名,这样我的每个消费者都可以在服务器端日志应该有问题。

有没有办法可以做到这一点?我查看了spring引导参考指南和java.lang.System类,但找不到富有成效的指针。

2 个答案:

答案 0 :(得分:2)

这是一种方法 - 在您的配置中添加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被覆盖。

答案 1 :(得分:0)

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;}