This is the 31st day of my participation in the August Text Challenge.More challenges in August

🌈 Column Introduction

Thank you for reading, I hope to help you, if there is a flaw in the blog, please leave a message in the comment area or add my private chat in the home page, thank you for every little partner generous advice. I am XiaoLin, a boy who can both write bugs and sing rap. This column mainly introduces the most mainstream micro services solution, SpringCloudAlibaba, which will be introduced in groups. Column address: SpringCloudAlibaba

  • 8️ Sleuth and Zipkin (suggested collection)
  • 7️ Gateway (suggested collection)
  • 6️ Sentinel (suggested collection)
  • 5️ retail Feign
  • 4️ Ribbon (suggested collection)
  • 3️ Nacos (suggested collection)
  • 2️ retail (suggested collection)
  • 1️ retail (suggested collection)

Eleven: Service configuration center: Nacos Config

11.1 Introduction to service Configuration Center

First, let’s take a look at some of the problems with configuration files in microservices architecture:

  1. Configuration files are scattered. In a microservice architecture, configuration files become more and more as the number of microservices increases, and are scattered in various microservices, making unified configuration and management difficult.
  2. Configuration files cannot distinguish between environments. Microservice projects may have multiple environments, such as a test environment, a pre-release environment, and a production environment. The configuration used by each environment is theoretically different, and once it needs to be modified, we need to manually maintain it in each microservice, which is difficult.
  3. The configuration file cannot be updated in real time. After we changed the configuration file, we had to restart the microservice for the configuration to take effect, which was very unfriendly for a running project. Based on these problems, we need to add a configuration center to solve these problems.

The configuration center is as follows:

  1. Firstly, all the configurations in the project are put into a centralized place for unified management, and a set of standard interfaces are provided.
  2. When each service needs to obtain configuration, it pulls its own configuration from the interface in the configuration center.
  3. When various parameters in the configuration center are updated, it can also notify each service to synchronize the latest information in real time and update it dynamically.

After joining the service Configuration Center, our system architecture diagram will look like this:

Common service configuration centers in the industry include:

  1. Apollo

    Apollo is a distributed configuration center open source by Ctrip. There are many features, such as: configuration updates can take effect in real time, support grayscale publishing function, and can carry out version management for all configurations, operation audit and other functions, provide open platform API. And the information is very detailed.

  2. Disconf

    Disconf is a distributed configuration center developed by Baidu. It is based on Zookeeper to realize real-time notification and implementation of configuration changes.

  3. SpringCloud Config

    This is the configuration center component that comes with Spring Cloud. It integrates seamlessly with Spring and is very easy to use, and its configuration store supports Git. However, there is no visual interface, and configurations do not take effect in real time, requiring a reboot or refresh.

  4. This is a component in the SpingCloud Alibaba technology stack that we have already used as a service registry. In fact, it also integrates service configuration functions, so we can use it directly as a service configuration center.

11.2 getting started with Nacos Config

Using NACOS as the configuration center is actually to treat NacOS as a server and each microservice as a client. We store the configuration files of each microservice uniformly on NacOS, and then each microservice can pull the configuration from NacOS.

Introduce dependencies in commodity microservices

<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
Copy the code

Add nacOS Config configuration to microservices

Instead of using the original application.yml as the configuration file, create a new bootstrap.yml configuration file.

Properties -> bootstrap.yml -> application.properties -> application.yml

Comment out the original YML configuration file, leaving only the unique configuration, such as port, service name and so on.

spring:
  application:
    name: product-service
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848 #nacos Center address
        file-extension: yaml Configuration file format
  profiles: 
  	active: dev # Environment identification
Copy the code

Add the configuration to NACOS, and then copy the order microservice application.yml configuration to the configuration content

Interpret the contents of local application.yam and launch the program for testing

11.3. Dynamically refresh the Nacos Config configuration

We have realized the remote storage of the configuration. However, if the configuration is modified, our program cannot read it. Therefore, we need to enable the dynamic refresh function of the configuration.

This configuration in the order-service-dev.yaml configuration item in NACOS (must be on a remote configuration file, not local)

config:
	appName: order To test dynamic refresh when changing parameters, see if it can be refreshed dynamically
Copy the code

NacosConfigControlller was added to the Order microservice

@RestController
@RefreshScope // Implement dynamically refreshed annotations
public class NacosConfigController {
    @Value("${appConfig.name}")
    private String appConfigName;
    @RequestMapping("/nacosConfig1")
    public String nacosConfig(a){
        return "Remote information :"+appConfigName; }}Copy the code

11.4. Nacos Config Configure sharing

As the number of configurations increases, we find that many configurations are duplicated. At this point, we need to consider extracting the common 1 configuration file and implementing the configuration file sharing, who needs to import directly.

11.4.1. Sharing configurations between different environments of the same microservice

If you want to implement configuration sharing between different environments of the same microservice, you just need to extract one with spring.application.name (spring. Service name), and then put the common configuration for all its environments in it.

Create a new order-service.yaml configuration file

This configuration file is used to store common configuration files.

server:
  port: 8080
  tomcat:
    threads:
      max: 10 # change the maximum concurrency of tomcat to 10.
spring:
  zipkin:
    base-url: http://127.0.0.1:9411/ #zipkin server request address
    discoveryClientEnabled: false Have nacos treat it as a URL, not as a service name
    sleuth:
      sampler:
        probability: 1.0 # Percentage of samples
  application:
    name: order-service
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///shop-product? serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: 1101121833
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        port: 9999 Select an unused port to communicate with the console
        dashboard: localhost:8080 Specify the address of the console service
      web-context-unify: false
  jpa:
    properties:
      hibernate:
        hbm2ddl:
          auto: update
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
product-service: The name of the provider being invoked
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
feign:
  client:
    config:
      default:
        connectTimeout: 3000
        readTimeout: 3000
Copy the code

Create a new order-service-test.yaml configuration file

This configuration file is used to store the configuration of the test environment.

appConfig:
  name: order-service
env: dev
server:
    application:
        name: order-service
spring:
  application:
    name: order-service The name of the service
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848 #nacos Center address
        file-extension: yaml Configuration file format
Copy the code

Add test methods to Controller

@RestController
@RefreshScope
public class NacosConfigController {
    @Value("${appConfig.name}")
    private String appConfigName;
    @Value("${env}")
    private String env;
    @RequestMapping("/nacosConfig1")
    public String nacosConfig(a){
        return "Remote information :"+appConfigName;
    }
    @RequestMapping("/nacosConfig2")
    public String nacosConfig2(a){
        return "Common configuration :"+appConfigName+", environment configuration information :"+env; }}Copy the code

11.4.2 Configuration of sharing among different micro services

The principle of configuration sharing between different services is similar to file import, that is, define a common configuration and import it in the current configuration.

Define a global-config.yaml configuration file in nacOS

This configuration file is used to store the configuration shared by all microservices. Write a property for testing purposes.

globalConfig: global
Copy the code

Modify the bootstrap. Yaml

spring:
  application:
    name: order-service The name of the service
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848 #nacos Center address
        file-extension: yaml Configuration file format
        shared-configs:
          - data-id: global-config.yaml Configure the configuration to be imported
            refresh: true
  profiles:
    active: test # Environment identification
Copy the code

Modify the side method of 1Controller

@RestController
@RefreshScope
public class NacosConfigController {
    @Value("${appConfig.name}")
    private String appConfigName;
    @Value("${env}")
    private String env;
    @Value("${globalConfig}")
    private String globalConfig;
    @RequestMapping("/nacosConfig1")
    public String nacosConfig(a){
        return "Remote information :"+appConfigName;
    }
    @RequestMapping("/nacosConfig2")
    public String nacosConfig2(a){
        return "Common configuration :"+appConfigName+", environment configuration information :"+env;
    }
    @RequestMapping("/nacosConfig3")
    public String nacosConfig3(a){
        return "Global Configuration :"+globalConfig+", common configuration:+appConfigName+", environment configuration information :"+env; }}Copy the code

test

11.5 Some concepts of NACOS

  1. Namespace (Namespace)

    Namespaces can be used for configuration isolation of different environments. Typically an environment is divided into a namespace.

  2. Configuring Groups

    Configuration groups are used to group different services into the same group. Typically, the configuration of a project is grouped into groups.

  3. Configuration set (Data ID)

    In a system, a configuration file is usually a configuration set. A typical microservice configuration is a configuration set.