I am creating a Spring Boot
application, which will read configuration like DB properties from Consul
. But I am not able to read the key value from Con
You can find a working example here.
You need to store your properties in the Consul KV store either from Consul UI or from the command line. The Consul Agent will not load your properties from the file system. To load the properties from the command line, you can use the following command once the Consul Agent is up and running. The YAML data can be read from a file by prefixing the file name with the @ symbol.
./consul kv put config/application/data @spring-boot-consul.yml
where config/application/data
is the key name.
If the data is successfully written in the KV, you should get the following response,
Success! Data written to: config/application/data
You can also fetch the properties from the KV by using the following command,
$ ./consul kv get config/application/data
cassandra:
host: 127.0.0.1:9042,127.0.0.2:9042
user: my_user
password: my_pass
You can also view the properties from the Consul Web UI,
You need to modify your bootstrap.yml
slightly. Here are the changes:
prefix
value to config
defaultContext
value to application
format
to yaml
Added data-key
by the name of data
to fetch the YAML blob.
spring:
profiles: default
cloud:
consul:
host: localhost
port: 8500
config:
enabled: true
prefix: config
defaultContext: application
data-key: data
profileSeparator: '::'
format: yaml
application:
name: spring-boot-consul
@Configuration
@RefreshScope
public class ConsulConfiguration {
@Value("${cassandra.host}")
private String cassandraHost;
@Value("${cassandra.user}")
private String userName;
@Value("${cassandra.password}")
private String password;
@PostConstruct
public void postConstruct() {
// to validate if properties are loaded
System.out.println("** cassandra.host: " + cassandraHost);
System.out.println("** cassandra.user: " + userName);
System.out.println("** cassandra.password: " + password);
}
}
@EnableRetry
@RefreshScope
@EnableDiscoveryClient
@EnableAutoConfiguration
@EnableConfigurationProperties
@SpringBootApplication
@ComponentScan("com.test.*")
public class SpringBootConsulApplication {
public static void main(String[] args) {
...
}
}