问题
I am working on a project with Spring-Kafka and Boot and am wanting to get the hostname in the application.properties for the property spring.kafka.consumer.client-Id so that each of my consumers can be distinguished in the server side logs should there be an issue.
Is there a way i could do that? I check on the spring boot reference guide and java.lang.System class but could not find fruitful pointers.
回答1:
Here's one way - add an EnvironmentAware bean to your config...
@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();
}
}
}
In this case, I did it in the boot app itself but it can be done in any 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
As you can see, the client-id is overridden.
来源:https://stackoverflow.com/questions/43191948/spring-boot-getting-the-hostname-in-application-properties-for-spring-kafka-cl