SCA Nacos service registry and configuration center

Nacos introduction

Nacos (Dynamic Naming and Configuration Service) is an open source platform of Alibaba for Service discovery, Configuration management, and Service management in micro-service architecture. Nacos is the combination of registry + configuration center (Nacos=Eureka+Config+Bus)

Nacos. IO download address: github.com/alibaba/Nac…

Nacos features

  • Service discovery and health check
  • Dynamic configuration Management
  • Dynamic DNS Service
  • Services and metadata management (from the management platform perspective, NacOS also has a UI page where you can see registered
  • Services and their instance information (metadata information), dynamic service weighting, dynamic service gracefully offline, can be done

Nacos singleton service deployment

  • Open the GitHub address and download the Tagz package. Here we are using version 1.2.0

  • Download the unzip package and run the command to start (we used the most recent stable version nacos-server-1.1.0.tar.gz).
Linux/MAC: sh startup. Sh -m standalone Windows: CMD startupCopy the code

  • Access nacos management interface: http://127.0.0.1:8848/nacos/#/login (the default port 8848, account and password nacos/nacos)

Nacos Service registry

Service providers register with Nacos(Retrofit Resume Microservices)

  • Introduce SCA dependencies in the parent POM
<dependencyManagement>
 <dependencies>
     <! --SCA -->
     <dependency>
         <groupId>com.alibaba.cloud</groupId>
         <artifactId>spring-cloud-alibaba-dependencies</artifactId>
         <version>2.1.0. RELEASE</version>
         <type>pom</type>
         <scope>import</scope>
     </dependency>
 </dependencies>
 <! --SCA -->
</dependencyManagement>
Copy the code
  • Added resume microservice: Lagou-service-resume-8082-nacos

  • Introducing nacOS client dependencies in service provider projects (annotated Eureka client)
<dependency>
 <groupId>com.alibaba.cloud</groupId>
 <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code
  • Application. Yml, add nacOS configuration information,
 server:
  port: 8082
spring:
  application:
    name: lagou-service-resume
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/lagou? useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2B8
    username: root
    password: root
  jpa:
    database: MySQL
    show-sql: true
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl  Avoid converting hump names to underline names
  # nacos configuration
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
Copy the code

  • Start the resume microservice and look at the NacOS console

    • Resume microservices appear in the list of services

Temporary instance: If the client does not renew the heartbeat duration, the server considers that the client is unhealthy and deletes the client within a certain period of time

Persistent instances: unhealthy and will not be removed from this. The main scenario is that Mysql master/slave nodes can be retrieved from Nacos. If the server does not receive heartbeat in a certain period of time, the server proactively detects the heartbeat

The server treats temporary instances differently than persistent instances.

Protection threshold: can be set to a floating point number between 0 and 1, which is actually a scale value (current health instances of the service/total current instances of the service)

Scenario: In the general process, NACOS is the service registry, and service consumers need to obtain the available instance information of a service from NACOS. There are healthy or unhealthy service instances, and NACOS will return the healthy instance information to consumers when it is returned. At this time, there will be some problems in some high concurrency and heavy traffic scenarios

If the service has 100 examples, A 98 instances are not healthy, only two instances is healthy, if the nacos returns only two examples of health information, all subsequent requests of consumers will be assigned to the two examples, traffic flow, 2 cases of health also carry not to live, the entire service A it carry not to live, Upstream microservices can also crash, creating an avalanche effect.

Meaning of protection threshold

When the number of healthy instances/total instances of service A is less than the protection threshold, it means that there are really few healthy instances and the protection threshold will be triggered (state true)

Nacos will provide all the instance information (healthy + unhealthy) of the service to the consumer, who may access an unhealthy instance and fail, but this is better than causing an avalanche, sacrificing some requests and ensuring that the entire system is available

Service consumers get service providers from Nacos (transform automated delivery microservices)

  • Create a new project

  • Pom files retain only necessary dependencies
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

</dependencies>
Copy the code
  • application.yml
    • Configuration nacos
    • Configuration of ribbon
    • Configuration feign
    • Configuration loging
    • Configuration hystrix
server:
  port: 8097
spring:
  application:
    name: lagou-service-autodeliver
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
  Expose health interface details
  endpoint:
    health:
      show-details: always
# for the microservice name of the called party, if not added, it takes effect globally
lagou-service-resume:
  ribbon:
    Request connection timeout
    ConnectTimeout: 2000
    Request processing timeout
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Feign timeout value Settings
    ReadTimeout: 3000
    All operations are retried
    OkToRetryOnAllOperations: true
    #### Based on the configuration above, when a failed request is reached, it tries to access the current instance again (the number of times is specified by MaxAutoRetries).
    #### If not, another instance is accessed, if not, another instance is accessed (the number of changes is configured by MaxAutoRetriesNextServer),
    #### If you still fail, a failure message is displayed.
    MaxAutoRetries: 0 Number of retries for the currently selected instance, not including the first call
    MaxAutoRetriesNextServer: 0 Number of retries for switching instances
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule Load policy adjustment
logging:
  level:
    # Feign Logs respond only to logs with the log level debug
    com.lagou.edu.controller.service.ResumeServiceFeignClient: debug
# Enable Feign's fusing function
feign:
  hystrix:
    enabled: false
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Hystrix timeout value Settings
            timeoutInMilliseconds: 15000
Copy the code
  • Start the project and find that it is registered with NACOS

  • Testing usability

  • When the test is complete, you can view the subscriber list, which is only available in the new version, by entering the name of the service provider or grouping before you can query

Load balancing

When the Nacos client is introduced, it will be associated with the Ribbon dependency package. When we use OpenFiegn, we will also introduce the Ribbon dependency package. The Ribbon and Hystrix can be configured in the original way. Registering with Nacos makes it easier to test load balancing, as we can see in the background.

  • Create a new resume micro-service

  • Register with NACOS

  • Run several tests and find the output 8082 8083

  • We can go up and down a service instance

  • We can also edit the weight of service instances, so that if an instance of A is set to 1 and instance of B is set to 0, it is equivalent to sending instance B offline

Nacos Server data persistence

Nacos uses an embedded database by default for data storage, which supports switching to external Mysql storage

  • Create a new database, NACOS, and execute the table building script for NACOS

  • Modify the configuration file of nacOS

  • Unpack the database comments and modify the configuration information on the machine

  • Restarting NACOS completes data persistence

Nacos Server cluster

  • Install three or more Nacos and copy the extracted Nacos folders named NACOS-01, NACOS-02, and NACOS-03

  • Modifying a Configuration File

    • For the same machine simulation, change server.port in the application. Properties folder to 8848, 8849, 8850 respectively and bind IP to the current instance node as the server may bind multiple IP addresses
    Nacos. Inetutils. IP address = 127.0.0.1Copy the code
    • A copy of the conf/cluster. Conf. Example files, named cluster. The conf in the configuration file Settings information of each node in the cluster
    127.0.0.1:8848 127.0.0.1:8849 127.0.0.1:8850Copy the code
  • Start three instances

  • Server Cluster List

  • When a service fails, the remaining two nodes automatically vote

Nacos configuration center

  • Adding a namespace

  • Nacos Server Adds a configuration set

After adding namespaces, you can add a configuration set to each namespace, which is essentially adding a configuration file

DataId is the name of the configuration file

Microservices access Nacos

With the Nacos server built, we can enable Nacos configuration management in our microservices

  • Add the dependent
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
Copy the code
  • How to lock configuration files in Nacos Server in microservices (dataId)

Lock configuration files with Namespace + Group + dataId. If Namespace is not specified, the default is public; if Group is not specified, the default is DEFAULT_GROUP

The full format of dataId is as follows:

 ${prefix}-${spring.profile.active}.${file-extension}
Copy the code
  • Prefix for spring. The default application. The name of the value, but can be by spring configuration items. The cloud. Nacos. Config. The prefix to configuration.
  • Spring.profile. active is the profile corresponding to the current environment. Note: When spring.profile.active is null, the corresponding hyphen – will also not exist, and the dataId concatenation format becomes prefix.{prefix}.prefix.{file-extension}.
  • File – exetension as the configuration of content data format, can be configured a spring. Cloud. Nacos. Config. The file – the extension to the configuration. Currently, only properties and YAML types are supported.
server:
  port: 8082
spring:
  application:
    name: lagou-service-resume 

  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/lagou? useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2B8
    username: root
    password: root
  jpa:
    database: MySQL
    show-sql: true
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl  Avoid converting hump names to underline names
  # nacos configuration
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848
      
management:
  endpoints:
    web:
      exposure:
        include: "*"
Copy the code

The name of this configuration is lagou-service-resume.yaml

  • When starting the project, I found an error, and repeatedly compared the configuration files, and reported this error.

  • Yaml was changed from Appcliation. yaml to boostrap.yaml

In the Spring Cloud Config client, only bootstrap.yml can be used to obtain the config Server configuration.

  • If you want to load a custom configuration file, you can do so through Ext-config

Add the abc.yaml file to the configuration file first

Add a simple configuration

Then add the ext-config array configuration to the configuration file, which is also configured with abc.yaml

Config: server - addr: 127.0.0.1:8848127.00 0.1:8849127.00 0.1:8850 namespace: 76bd1a7b-c306-4d49-8c0d-e4e2cb5248a7 group: DEFAULT_GROUP file-extension: Yaml ## dataId: lagou-service-resume.yaml ext-config[0]: data-id: abc.yaml group: DEFAULT_GROUP refresh: True # Enable dynamic refresh of the extended dataIdCopy the code

  • The order of configuration files is incorrect

If there are keys with the same name in several configuration files, the loading order is

Default configuration file > Extension Configuration 1 > Extension Configuration 2