1 introduction

Visit pumpkin Talk www.pkslow.com for more exciting articles!

Docker & Kubernetes related article: Container Technology

Spring Cloud Config was introduced earlier, but for Kubernetes applications, you may need to read ConfigMap configuration. Let’s see how Springboot can easily read ConfigMap and Secret.

2. Integrate Spring Cloud Kubenetes

Spring Cloud Kubernetes provides Spring Cloud applications associated with Kubernetes services. We can also write Java programs to get Kubernetes features, but Spring does it for us.

2.1 Project Code

Introducing dependencies:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-kubernetes-config</artifactId>
</dependency>
Copy the code

All you need is Springboot Web and Spring Cloud Kubernetes Config. It’s easy.

Springboot boot class:

@SpringBootApplication
public class ConfigMapMain {
    public static void main(String[] args) { SpringApplication.run(ConfigMapMain.class, args); }}Copy the code

Prepare an EndPoint to display the read configuration information:

@RestController
public class PkslowController {
    @Value("${pkslow.age:0}")
    private Integer age;

    @Value("${pkslow.email:null}")
    private String email;

    @Value("${pkslow.webSite:null}")
    private String webSite;

    @Value("${pkslow.password:null}")
    private String password;

    @GetMapping("/pkslow")
    public Map<String, String> getConfig(a) {
        Map<String, String> map = new HashMap<>();
        map.put("age", age.toString());
        map.put("email", email);
        map.put("webSite", webSite);
        map.put("password", password);
        returnmap; }}Copy the code

The default is empty. The password is read from Secret and the rest is read from ConfigMap.

The application configuration file is as follows:

server:
  port: 8080
spring:
  application:
    name: spring-cloud-kubernetes-configmap
  cloud:
    kubernetes:
      config:
        name: spring-cloud-kubernetes-configmap
Copy the code

The spring here. Cloud. Kubernetes. Config. The name is a key, subsequent to find ConfigMap through it.

Encryption password:

$ echo -n "pkslow-pass" | base64 
cGtzbG93LXBhc3M=
Copy the code

Create Kubernetes Secret:

kind: Secret
apiVersion: v1
metadata:
  name: spring-cloud-kubernetes-secret
  namespace: default
data:
  pkslow.password: cGtzbG93LXBhc3M=
type: Opaque
Copy the code

The contents of ConfigMap are as follows:

kind: ConfigMap
apiVersion: v1
metadata:
  name: spring-cloud-kubernetes-configmap
  namespace: default
  labels:
    app: scdf-server
data:
  application.yaml: |- pkslow: age: 19 email: [email protected] webSite: www.pkslow.comCopy the code

Spring-cloud-kubernetes-configmap = spring-cloud-kubernetes-configmap = spring-cloud-kubernetes-configmap

Then complete the Dockerfile and K8s deployment file. Note that the value of Secret is mapped to the environment variable:

env:
	- name: PKSLOW_PASSWORD
		valueFrom:
			secretKeyRef:
				name: spring-cloud-kubernetes-secret
				key: pkslow.password
Copy the code

2.2 Startup and test

The application will go to Kubernetes to find the corresponding ConfigMap and Secret at startup:

____ ____ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | | | (_ | |))))' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.5. RELEASE) the 2020-08-25 00:13:17. 374 INFO 7 - [the main] B.C.P ropertySourceBootstrapConfiguration: Located property source: CompositePropertySource {name='composite-configmap', propertySources=[ConfigMapPropertySource {name='configmap.spring-cloud-kubernetes-configmap.default'}}] 2020-08-25 00:13:17. 376 INFO 7 - [the main] B.C.P ropertySourceBootstrapConfiguration: Located property source: CompositePropertySource {name='composite-secrets', propertySources=[]}
Copy the code

Access to spring – the cloud – kubernetes – configmap. Localhost/pkslow, can be read correctly configured, configmap and had access to the content of the Secret:

3 Automatically refresh the configuration

3.1 Principle and Code change

We need to modify the configuration and make it work while the Web is running, and there are several modes. Modify the configuration file as follows:

server:
  port: 8080
spring:
  application:
    name: spring-cloud-kubernetes-configmap
  cloud:
    kubernetes:
      config:
        name: spring-cloud-kubernetes-configmap
        namespace: default
      secrets:
        name: spring-cloud-kubernetes-secret
        namespace: default
        enabled: true
      reload:
        enabled: true
        monitoring-config-maps: true
        monitoring-secrets: true
        strategy: restart_context
        mode: event
management:
  endpoint:
    restart:
      enabled: true
  endpoints:
    web:
      exposure:
        include: restart
Copy the code

(1) spring. Cloud. Kubernetes. Reload. Enabled = true need to open the refresh function;

(2) Loading strategy:

  • refreshNote: Takes effect only for specific configurations@ConfigurationProperties@RefreshScope.
  • restart_context: the wholeSpring ContextIt will reboot gracefully, and everything in it will be reloaded.

Configure management. Endpoint because the actuator endpoint needs to be enabled. Also add dependencies:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-actuator-autoconfigure</artifactId>
</dependency>
Copy the code
  • shutdown: Restarts the container.

(3) Mode mode

  • The eventEvent: will passk8s APImonitoringConfigMapTo read the configuration and take effect.
  • Polling: Periodically checks whether there is a change. If there is a change, the alarm is triggered. The default value is 15 seconds.

3.2 test

Let’s modify the ConfigMap configuration and update it to K8s.

$ kubectl apply -f src/main/k8s/config.yaml 
configmap/spring-cloud-kubernetes-configmap configured
Copy the code

Age and email have been changed:

The Pod log is as follows:

Springboot detects that the ConfigMap has been changed and triggers the Context to restart.

4 summarizes

Spring Cloud Kubernetes provides a number of Spring Cloud integration Kubernetes features, can be introduced to use.


Spring Cloud Kubernetes reads ConfigMap and supports automatic configuration refresh

Spring Cloud Config is easier to use in Spring Cloud Task than Web application

Spring Cloud Config integrates Spring Cloud Kubernetes to manage configuration on K8S

Use Spring Cloud Config to centrally manage configuration and stop leaving configuration files lying around

Properties (Common file system -classpath-jar-URL)

The @ConfigurationProperties annotation keeps the configuration neat and simple

I just want one article to document the use of @value. I don’t want to find anything else

Springboot integrates Jasypt to make configuration information secure in the most elegant and convenient way


Welcome to pay attention to the wechat public number “Pumpkin slow Talk”, will continue to update for you…

Read more and share more; Write more. Organize more.