Nacos service registration and configuration center

Introduction to Nacos

Nacos is an easy-to-use dynamic service discovery, configuration and service management platform for building cloud local applications. Through Spring Cloud Alibaba Nacos Discovery, you can quickly access the Nacos service registration function based on the programming mode of Spring Cloud.

Service discovery is one of the key components in microservice architecture. In such an architecture, manually configuring the service list of each client can be a difficult task, which makes dynamic scaling extremely difficult. Nacos Discovery helps automatically register your services with the Nacos server, which tracks these services and dynamically refreshes the service list. In addition, Nacos Discovery registers some metadata of the service instance (such as host, port, health check URL, home page) with Nacos.

In general, Nacos is the combination of registration center and configuration center. Nacos=Eureka+Config+Bus

Nacos installation

  1. Java 8 + Maven environment dependency needs to be installed locally

  2. Download n from the official website acoshttps://github.com/alibaba/nacos/releases

  3. Unzip the installation package and directly run startup.exe under the bin directory cmd

  1. Direct access after the command runs successfully http://localhost:8848/nacos The default login account password is Nacos

Nacos service registry

Nacos service provider registration

Introduce dependency

spring-cloud-starter-alibaba-nacos-discovery

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

configuration file

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

Main startup class

EnableDiscoveryClient

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9001 {

Visit nacos8848

Nacos service consumer registration and load

Integrated ribbon with load balancing

Introduce dependency

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

Configure RestTemplate

@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
    return new RestTemplate();
}

Load remote call

@Resource
private RestTemplate restTemplate;

@GetMapping("/consumer/payment/nacos/{id}")
public String paymentInfo(@PathVariable("id") Integer id) {
    return restTemplate.getForObject("http://nacos-payment-provider" + "/payment/nacos/" + id, String.class);
}

Comparison and improvement of Nacos service registration center

CAP: Consistency, Availability, Partition tolerance. C is that all nodes see the same data at the same time; The definition of A is that all requests will receive A response.

When to choose which mode to use?

Generally speaking, if you do not need to store service level information, and the service instance is registered through Nacos city and can maintain heartbeat reporting, you can choose AP mode. The current mainstream services, such as Spring cloud and Dubbo services, are applicable to the AP mode. The AP mode weakens the consistency for the possibility of services. Therefore, only temporary instances can be registered in the AP mode. If you need to edit or store configuration information at the service level, CP is required, and K8S service and DNS service are applicable to CP mode. In CP mode, persistent instance registration is supported. At this time, the Raft protocol is used as the cluster operation mode. In this mode, the service must be registered before registering the instance. If the service does not exist, an error will be returned.

Switch CP+AP

curl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP'

curl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=AP'

Nacos service configuration center

Nacos as configuration center - basic configuration

Nacos is the same as spring cloud config. During project initialization, it is necessary to pull the configuration from the configuration center first. After pulling the configuration, the normal startup of the project can be guaranteed. There is a priority order for loading configuration files in springboot, and the priority of bootstrap is higher than that of application

Introduce dependency

spring-cloud-starter-alibaba-nacos-config

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

configuration file

bootstrap.yml

server:
  port: 3377
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # Registration Center
      config:
        server-addr: localhost:8848 # Configuration center
        file-extension: yaml # The file format specified here needs to be the same as the suffix of the newly created configuration file on nacos, otherwise it cannot be read
        group: DEFAULT_GROUP
#  ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}

application.yml

spring:
  profiles:
    active: dev # development environment 
#    active: test # testing environment
#    active: info # development environment 

Configuration rules in Nacos

Formula: p r e f i x − {prefix}- prefix−{spring.profile.active}.${file-extension}

  • prefix defaults to spring application. Value of name
  • spring.profile.active is the profile corresponding to the current environment
  • File exception is the data format of the configuration content, which can be configured through the configuration item spring cloud. nacos. config. File extension

Nacos as configuration center - group configuration

In actual development, usually a system will prepare: dev development environment, test test environment and prod production environment. How to ensure that the service can correctly read the configuration file of the corresponding environment on Nacos when the specified environment is started. Multi environment and multi project configuration

Namespace+Group+Data ID

Default:

Namespace=public,Group=DEFAULT_GROUP, the default Cluster is default

The default Namespace is public Namespace.

For example, there are three environments: development, testing and production. You can create three namespaces, and different namespaces are isolated.

Group defaults to DEFAULT_GROUP and group can divide different micro services into the same group

DataID scheme

Specify spring profile. Active and the DataID of the configuration file enable different configurations to be read in different environments

Default space + default grouping + new dev and test dataids. Through spring profile. The active attribute can read configuration files in multiple environments

Group scheme

Add a group configuration under config Configurable as DEV_GROUP or TEST_GROUP

Namespace scheme

Create a new Namespace for dev/test /

Go back to service management - service list view

Fill in according to the domain name configuration

Nacos cluster and persistent configuration

Import nacos database script

application.properties configuration

spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://192.168.56.10:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=root

Cluster configuration of nacos on Linux server conf

Edit Nacos startup script startup SH to enable it to accept different boot ports

Usually, the startup of the stand-alone version is/ startup.sh is enough. However, for cluster startup, we hope to start different nacos instances by passing different port numbers similar to the shell commands of other software. Command:/ startup.sh -p 3333 indicates the nacos server instance with the startup port number of 3333 and the cluster in the previous step Conf configuration is consistent.

nohup $JAVA -Dserver.port=${PORT} ${JAVA_OPT} nacos.nacos

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-6qzELyRE-1619928776751)(... / appdata / roaming / typora / typora user images / image-20210502120414793. PNG)]

Nginx is configured as a load balancer

Modify profile

Add the following configuration

Starting nginx from a custom profile

Test access to nacos cluster

The test service is registered into the nacos cluster

Keywords: Spring Cloud

Added by nubby on Fri, 18 Feb 2022 05:13:36 +0200