springcloud之configuration

springcloud之configuration

*Spring Cloud Config* is Spring's client/server approach for storing and serving distributed configurations across multiple applications and environments.

Configuration store - git version control

use config : Environment, PropertySource or @Value

Dependency

spring-cloud-config-server

Config server

EnableConfigServer:

@SpringBootApplication
@EnableConfigServer
public class ConfigServer {

public static void main(String[] arguments) {
SpringApplication.run(ConfigServer.class, arguments);
}
}

config git url

server.port=8888
spring.cloud.config.server.git.uri=ssh://localhost/config-repo
spring.cloud.config.server.git.clone-on-start=true
spring.security.user.name=root
spring.security.user.password=s3cr3t

config file

file name : the value property ‘spring.application.name' of the client is used, followed by a dash and the active profile

$> git init
$> echo 'user.role=Developer' > config-client-development.properties
$> echo 'user.role=User' > config-client-production.properties
$> git add .
$> git commit -m 'Initial config-client properties'

config-client-${profile}.properties

  • user.role=Developer
  • user.role=User

query config

Path

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

eg : curl http://root:s3cr3t@localhost:8888/config-client/development/master

SpringBootApplication
@RestController
public class ConfigClient {

@Value("${user.role}")
private String role;

public static void main(String[] args) {
SpringApplication.run(ConfigClient.class, args);
}

@GetMapping(
value = "/whoami/{username}",
produces = MediaType.TEXT_PLAIN_VALUE)
public String whoami(@PathVariable("username") String username) {
return String.format("Hello!
You're %s and you'll become a(n) %s...\n", username, role);
}
}

bootstrap.properties

spring.application.name=config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.username=root
spring.cloud.config.password=s3cr3t

Encrytion/Decryption

The config server is per default enabled to encrypt property values in a symmetric or asymmetric way.

To use symmetric cryptography, you simply have to set the property ‘encrypt.key' in your application.properties to a secret of your choice. Alternatively you can pass-in the environment variable ENCRYPT_KEY.

For asymmetric cryptography, you can set ‘encrypt.key' to a PEM-encoded string value or configure a keystore to use.