Nacos Service registry and configuration center

Introduction to Nacos

1. Why is it called Nacos

The first four letters are the first two letters of Naming and Configuration respectively, and the last “s” is Service.

2. What is it

A dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud-native applications.

Nacos: Dynamic Naming and Configuration Service

Nacos is registry + configuration center combination ==Nacos = Eureka+Config +Bus

3. What can I do

Replace Eureka as the service registry and Config as the service configuration center

4. Where to go

Download at github.com/alibaba/nac…

Nacos. IO /zh-cn/index…

Spring – the cloud – alibaba – group. Making. IO/lot – page…

5. Comparison of various registries

Install and run Nacos

1. The local Java8+Maven environment is OK

2. Download Nacos from the official website first

Github.com/alibaba/nac…

Select the current version 2.0.3 here

3. Decompress the installation package

Run startup. CMD in the bin directory

About startup errors: Double-click startup. CMD directly to run nacos as a cluster, so you need to add parameters to run it in standalone mode

startup.cmd -m standalone
Copy the code

4. After the command is run successfully

Direct access: http://localhost:8848/nacos

The default account password is nacos

5. Result interface

Nacos as a service registry demo

1. Official website documents

Spring – the cloud – alibaba – group. Making. IO/lot – page…

2. Nacos-based service provider

(1) the new Module

cloudalibaba-provider-payment9001

(2)POM

(1) the father POM

<! --spring cloud alibaba2.2. 0.RELEASE--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId>  <version>2.2. 0.RELEASE</version>
  <type>pom</type>
  <scope>import</scope>
</dependency>
Copy the code

② POM of this module

<! --SpringCloud ailibaba nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>Copy the code

(3)YML

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # Configure Nacos address

management:
  endpoints:
    web:
      exposure:
        include: The '*'
Copy the code

(4)

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

(5) business class

@RestController
public class PaymentController {
    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id) {
        return "nacos registry, serverPort: "+ serverPort+"\t id"+id; }}Copy the code

(6) test

http://localhost:9001/payment/nacos/1

Nacos console

(7) Create 9002 by referring to 9001

To demonstrate nacOS load balancing in the next section, create cloudalia-Provider-Payment9002

Or copy a virtual port mapping:

3. Nacos-based service consumers

(1) the new Module

cloudalibaba-consumer-nacos-order83

(2)POM

<! --SpringCloud ailibaba nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>Copy the code

(3)YML

server:
  port: 83


spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848


# Name of the microservice that the consumer is going to access (microservice provider that registered successfully with NACOS)
service-url:
  nacos-user-service: http://nacos-payment-provider 
Copy the code

(4)

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

(5) business class

1) ApplicationContextBean

@Configuration
public class ApplicationContextBean {// Because the ribbon will be introduced
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(a) {
        return newRestTemplate(); }}Copy the code

(2) OrderNacosController

@RestController
@Slf4j
public class OrderNacosController {
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")// Separate the configuration from the code
    private String serverURL;

    @GetMapping("/consumer/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id) {
        return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class); }}Copy the code

(6) test

Nacos console

http://localhost:83/consumer/payment/nacos/13

83 Access 9001/9002 and the polling load is OK

4. Service registry comparison

C:Consistency

A:Availability

P:Partition tolerance

Nacos and CAP

Nacos supports switching between AP and CP modes

C is that all nodes see the same data at the same time; And the definition of A is that all requests receive A response.

When to choose which mode to use?

In general, the AP mode can be selected if the storage service level information is not required and the service instance is registered with nacOS-Client and can maintain heartbeat reporting. The current mainstream services, such as Spring Cloud and Dubbo services, are applicable to the AP pattern, which is less consistent for service possibilities, so only temporary instance registration is supported under the AP pattern. If you need to edit or store configuration information at the service level, CP is a must, and the K8S service and DNS service are suitable for CP mode. In this mode, the Raft protocol is used as the cluster mode. In this mode, the service must be registered before the instance is registered. If the service does not exist, an error will be returned.

Demonstration of Nacos as a service configuration center

1, Nacos as the configuration center – basic configuration

(1) the new Module

cloudalibaba-config-nacos-client3377

(2)POM

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

(3)YML

Nacos is the same as SpringCloud-Config. During the initialization of the project, it is necessary to ensure that the configuration is pulled from the configuration center first. Only after the configuration is pulled can the normal startup of the project be guaranteed.

In SpringBoot, configuration files are loaded in priority order. Bootstrap has a higher priority than application.

(1) the bootstrap

# nacos configuration
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos Service registry address
      config:
        server-addr: localhost:8848 #Nacos as the configuration center address
        file-extension: yaml Specifies the yamL configuration


# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml
Copy the code

(2) application

spring:
  profiles:
    active: dev # indicates the development environment
Copy the code

(4)

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

(5) business class

@RestController
@RefreshScope // Add the @refreshScope annotation to the controller class to enable the configuration of the current class to support Nacos dynamic refresh.
public class ConfigClientController {
    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/config/info")
    public String getConfigInfo(a) {
        returnconfigInfo; }}Copy the code

(6) Add configuration information in Nacos

(1) theory

The composition format of dataid in Nacos and matching rules in SpringBoot configuration file

Liverpoolfc.tv: nacos. IO/useful – cn/docs /…

The final formula: ${spring. Application. The name} – ${spring. Profiles. The active}. ${spring. Cloud. Nacos. Config. File – the extension}

(2) field

Set the DataId:

Historical configuration: Nacos records that the historical version of the configuration file is retained for 30 days by default. There is also a one-click rollback function that triggers configuration updates.

(7) test

Before the startup, you need to have the corresponding YAML configuration file under the nacOS client-Configuration Management-Configuration Management column. Run cloud-config-nacos-Client3377’s main startup class and invoke the interface to view the configuration information: http://localhost:3377/config/info

(8) Built-in dynamic refresh

Modify the YAML configuration file in Nacos and call the interface to view the configuration again. You will find that the configuration has been refreshed.

2, Nacos as the configuration center – classification configuration

(1) problem

Multi-environment multi-project management

Problem 1: In actual development, usually a system will prepare dev development environment, test test environment, and PROd production environment. How do you ensure that the configuration file on Nacos for the specified environment is correctly read by the service when the environment is started?

Problem 2: A large distributed microservice system will have many microservice sub-projects, and each microservice project will have corresponding development environment, test environment, pre-development environment and formal environment…… So how do you manage these microservice configurations?

(2) GRAPHICAL management interface of Nacos

Configuration management, namespace

(3)Namespace+Group+Data ID relationship? Why?

1) what is

Similar to package names and class names in Java. The outermost namespace is used to distinguish the deployment environment, and the Group and DataID logically distinguish the two target objects.

② The three cases

By DEFAULT, Namespace=public, Group=DEFAULT_GROUP, and DEFAULT Cluster is DEFAULT.

The default Namespace of Nacos is public. Namespace is used for isolation. Let’s say we have three environments: development, test, and production, and we can create three namespaces that are isolated from each other.

The default Group is DEFAULT_GROUP, which can be used to Group different microservices into the same Group.

Service is a microservice; A Service can contain multiple clusters (clusters). The DEFAULT Nacos Cluster is DEFAULT, and Cluster is a virtual division of a specified microservice. For example, in order to disaster recovery, the Service microservice is deployed in Hangzhou room and Guangzhou room respectively. At this time, we can give the Service microservice in Hangzhou room a cluster name (HZ), and the Service microservice in Guangzhou room a cluster name (GZ). We can also try to let the microservices in the same room call each other. To improve performance.

Finally, there is Instance, which is the Instance of the microservice.

(4) Load configuration of three schemes

1) DataID scheme

Specify spring.profile.active and the DataID of the configuration file to read different configurations for different environments and load whatever the configuration is.

Default space + default group + create two DataID dev and test

(2) the Group plan

To realize environment differentiation through Group, create a configuration file DataID on the NACOS GUI console.

Bootstrap + Application: Add a group under config. This can be configured as DEV_GROUP or TEST_GROUP.

(3) the Namespace solution

To create a Namespace for dev/test, enter the domain name

bootstrap

# nacos configuration
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos Service registry address
      config:
        server-addr: localhost:8848 #Nacos as the configuration center address
        file-extension: yaml Specifies the yamL configuration
        group: DEV_GROUP
        namespace: 3d804068-05c0-47c1-a7da-5dbb2f41120f
Copy the code

application

spring:
  profiles:
    active: dev # indicates the development environment
    #active: test # indicates the test environment
    #active: Info # indicates the development environment
Copy the code

5. Nacos clustering and persistence configuration (important)

1, the official website description

Address: nacos. IO/useful – cn/docs /…

By default, Nacos uses an embedded database for data storage. Therefore, if you start more than one Nacos node in the default configuration, the data store is inconsistent. To solve this problem, Nacos has adopted a centralized storage approach to support clustered deployment, currently only MySQL storage is supported.

Nacos. IO /zh-cn/docs/…

2. Explanation of Nacos persistence configuration

By default, Nacos ships with an embedded database Derby: github.com/alibaba/nac…

Derby to mysql switch configuration step: Nacos-server-1.1.4 \nacos\conf directory to find the SQL script nacos-mysql. SQL, execute the script, and then in nacos-server-1.1.4\nacos\conf directory to find the application.properties, Then add the following code:

spring.datasource.platform=mysql
 
db.num=1
db.url. 0=jdbc:mysql://127.0. 01.:3306/nacos_config? characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=trueFor higher versions, add the time zone db.user=root
db.password=123456Your own account passwordCopy the code

Start Nacos, and you’ll see a new, empty recording interface that was previously recording into Derby.

3, Linux version of Nacos+MySQL production environment configuration

It is estimated that 1 Nginx (virtual IP) +3 NACOS registries +1 mysql is required

(1)Nacos download Linux version

Github.com/alibaba/nac… , select nacos-server-1.1.4.tar.gz, decompress it and install it

(2) Cluster Configuration Procedure (Key)

① Configure the mysql database on the Linux server

Where is the SQL script

SQL statement source file: nacos-mysql.sql

Mysql database on your own Linux machine

(2) application. The properties configuration

At the end of the opened application. Properties file, configure the following:

③ The nacOS cluster configuration on the Linux server is cluster.conf

Sort out the different service port numbers of the three NACOS aggregators and copy cluster.conf

The IP address cannot be 127.0.0.1, but must be recognized by the Linux command hostname -i

4. Edit the startup script startup.sh of Nacos so that it can accept different startup ports

If startup.sh is found in the /mynacos/nacos/bin directory, use./startup.sh to start the stand-alone version.

But for cluster startup, we want to be able to start different NACOS instances by passing different port numbers similar to shell commands of other software. Run the./startup.sh -p 3333 command to start the nacOS server instance whose port number is 3333. The command is the same as that configured in the cluster.conf step.

⑤Nginx is configured as a load balancer

Modify the nginx configuration file nginx.conf

Start as specified

⑥ As of this point, 1 Nginx+3 NACOS registries +1 mysql

Testing nacos in nginx visit: http://192.168.111.144:1111/nacos/#/login

Create a new configuration test

Linux server mysql insert a record

(3) test

Micro service Cloudalia-Provider-Payment9002 starts registering with the NACOS cluster

server:
  port: 9002

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        # Configure Nacos address
        #server-addr: localhost:8848
        Switch to nginx port 1111 for cluster
        server-addr: 192.168111.144.: 1111


management:
  endpoints:
    web:
      exposure:
        include: The '*'
Copy the code

Test results:

(4)