This is the 16th day of my participation in Gwen Challenge.

For a long time, people playing With SpringCloud have been playing with SpringBoot1. x. Springcloud(Dalston version) has many related components to do configuration center, service registration and discovery, gateway uses Netflix LB for SpringBoot, etc. But these things are too heavy and complicated. In a K8S-BASED IaAS service system, it doesn’t make sense to do this without using k8S features. The reasons for this will not be repeated. In a word: Reduce the complexity of system services.

This paper mainly introduces the configuration management of SpringCloud combined with K8S to avoid the redundancy of more service components.

In actual combat

Environment:

  • ubuntu16.04

  • docker18.04

  • K8s1. 13. + x

  • maven3.5.3

  • Java1.8 +

  • Springboot 2.1.1

  • Spring – the cloud – kubernetes: 1.0.1. RELEAS

The premise

Install Docker18.04 or other later versions in Ubuntu, K8s1.13.x or above, JVM environment, etc.

Create a project

The dependency of spring-Cloud-Kubernetes on configMap should be added to k8S-BASED configuration management:

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

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

If there are operations redis and db, introduce the corresponding dependencies:

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> < version > 1.1.1 < / version > < / dependency > < the dependency > < groupId > mysql < / groupId > <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <! Pagehelper </groupId> <artifactId> pageHelper </artifactId> <version>${pageHelper.version}</version> </dependency> <! -- datasource pool--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> < version > 1.1.3 < / version > < / dependency > < the dependency > < groupId > org. Springframework. Boot < / groupId > <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> . < version > 1.4.7 RELEASE < / version > < / dependency >Copy the code

Redis, redis, redis, redis, redis, redis

@SpringBootApplication(scanBasePackages = { "com.leinao" })
@EnableConfigurationProperties(EnvConfig.class)
@EnableDiscoveryClient
@EnableHystrix
@EnableScheduling
public class AdminApp {
	public static void main(String[] args) {
		SpringApplication.run(AdminApp.class, args);
	}
}
Copy the code

Here joined the annotation: EnableConfigurationProperties, is to introduce the configuration management class, in this way, through management class attribute assignment. At the same time, if there is a service registration and discovery function, you can add @enableDiscoveryClient here.

Note that when creating the startup class, the SpringBoot project is optimized to avoid heavy startup load. For detailed optimization, please refer to mp.weixin.qq.com/s?__biz=MzU…

Do not create the application. Yml file in the SRC \main\resources path of the project. Only create the file named bootstrap.yml:

management:
  endpoint:
    restart:
      enabled: true
    health:
      enabled: true
    info:
      enabled: true

spring:
  application:
    name: edge-admin
  cloud:
    kubernetes:
      config:
        sources:
         - name: ${spring.application.name}
           namespace: default
      discovery:
        all-namespaces: true
      reload:
        enabled: true
        mode: polling
        period: 500
Copy the code

Here, we set the automatic configuration update switch to on and update the configuration information at the same time: polling is an active fetching interval of 500 milliseconds. You can also set event to be an event notification.

In this case, I created the bootstrap file and added the application file. Bootstrap will be loaded first during startup.

In application.yaml, we add the following:

server:
  port: 9999
  undertow:
    accesslog:
      enabled: false
      pattern: combined
  servlet:
    session:
      timeout: PT120M
Copy the code

Note: the server setting session timeout is completely different for springboot2.0 and 1.0, depending on the content.

Next configure the environment configuration:

The envconfig.java class is configured as an environment variable, annotating Prefix =”spring_cloud” for ConfigurationProperties,

Indicates that the configuration items used by this class are all children of the configuration item named “spring_cloud” :

package com.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "greeting") public class EnvConfig { private String message = "This is a dummy message"; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; }}Copy the code

Next, let’s write a demo interface:

@RestController public class DemoController { @Autowired private EnvConfig envConfig; @GetMapping(value = "/getMsg") public String getMsg() { return envConfig.getMessage(); }}Copy the code

Note: The default SVC does not have permission to access k8S API Server resources. Run the following script to increase the permission to access configMap:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: fabric8-rbac
subjects:
  - kind: ServiceAccount
    # Reference to upper's `metadata.name`
    name: default
    # Reference to upper's `metadata.namespace`
    namespace: default
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
Copy the code

Configuration configmap:

kind: ConfigMap
apiVersion: v1
metadata:
  name: edge-admin
data:
  application.yaml: |-
    greeting:
      message: Say Hello to the World
    ---
    spring:
      profiles: dev
    greeting:
      message: Say Hello to the Developers
Copy the code

It is time to execute the Deployment startup project:

apiVersion: apps/v1 kind: Deployment metadata: name: edge-admin-deployment labels: app: edge-admin spec: replicas: 1 selector: matchLabels: app: edge-admin template: metadata: labels: app: edge-admin spec: nodeSelector: edge-admin: "True" containers: - name: edge - admin image: 10.11.2.20:8000 / harbor/edge - admin imagePullPolicy: IfNotPresent ports: - name: admin01 containerPort: 1002 volumeMounts: - mountPath: /home/edge-admin name: edge-admin-path - mountPath: /data/edge-admin name: edge-admin-log-path - mountPath: /etc/kubernetes name: kube-config-path - mountPath: /abnormal_data_dir name: abnormal-data-dir args: ["sh", "-c", "nohup java $JAVA_OPTS -jar -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Xms1024m -Xmx1024m -Xmn256m -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC edge-admin.jar --spring.profiles.active=dev", "&"] hostAliases: - ip: "10.10.1.5" hostnames: - "k8s.api.server" - "foo.remote" -ip: "127.0.0.1" Hostnames: - "foo.localhost" -ip: "0.0.0.0" hostnames: - "foo.all" #serviceAccount: config-reader #serviceAccountName: config-reader volumes: - name: edge-admin-path hostPath: path: /var/pai/edge-admin - name: edge-admin-log-path hostPath: path: /data/edge-admin - name: kube-config-path hostPath: path: /etc/kubernetes - name: abnormal-data-dir hostPath: path: /data/images/detect_result/defectCopy the code

Among them, the project startup parameters described earlier to optimize its performance are the parameter Settings for the JVM. Execute kubectl apply -f deployment.yaml and configmap.yaml respectively, the configmap resources used to create the demo, and start the project with k8S deployment.

IP :port/getMsg: IP :port/getMsg: IP :port/getMsg

The above is to use the ConfigMap feature of SpringCloud and K8S for configuration management after the combination for the first time. The components of SpringCloud-Config and Spring-boot-starter -actuator are discarded to reduce the complexity of the system. After all, K8S is definitely going to be used, so you can use its features directly for environment configuration management of system services.