SpringCloud Alibaba Nacos service registration and configuration center

Posted by idire on Tue, 28 Dec 2021 13:03:01 +0100

1, Introduction to Nacos

Why Nacos
The first four letters of Nacos are the first two letters of Naming and Configuration respectively, and the last s is Service

What is Nacos
A dynamic service discovery, configuration management and service management center that is easier to build cloud native applications
Nacos: Dynamic Naming and Configuration Service
Nacos is the combination of registration center and configuration center, which is equivalent to Eureka+Config+Bus

Nacos can replace Eureka as the service registry and Config as the service configuration center

Download address: https://github.com/alibaba/Nacos

Official documents: https://nacos.io/zh-cn/index.html

https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-
alibaba.html#_spring_cloud_alibaba_nacos_discovery

Comparison of various registries

2, Install and run Nacos

Premise: the local Java8+Maven environment is OK

Download Nacos from the official website: https://github.com/alibaba/nacos/releases/tag/1.1.4

Unzip the compressed package, go to the bin directory, and edit startup CMD to change the default startup mode to stand-alone mode

Double click Startup CMD starts naocos. After the command runs successfully, you can access it directly http://localhost:8848/nacos , the access is successful. The default login account and password are all Nacos

3, Presentation of Nacos as a service registry

Parent POM

<!--spring cloud alibaba 2.1.0.RELEASE-->
<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>

service provider
Introducing pom into sub module

<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.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </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><dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>
 </dependencies>
 

YML configuration

server:
  port: 9001

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

management:
  endpoints:
    web:
      exposure:
        include: '*'

Main startup class

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

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

Service consumer

pom dependency

<dependencies>
    <!--SpringCloud ailibaba nacos -->
    <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.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </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>
 

YML configuration

server:
  port: 83


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


service-url:
  nacos-user-service: http://nacos-payment-provider

Main start

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

Business class

ApplicationContextBean

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

OrderNacosController

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

    @Value("${service-url.nacos-user-service}")
    private String serverURL;

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

}

Open the console

test http://localhost:83/consumer/payment/nacos/13 , 83 access 9001 / 9002, polling load OK

4, Service registry comparison

Nacos panorama

Nacos and CAP


Nacos supports switching between AP and CP modes

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?
In general,
If you do not need to store service level information, and the service instance is registered through the Nacos client and can maintain heartbeat reporting, you can select the AP mode. The current mainstream services, such as spin 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. In this case, 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.

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

5, Presentation of Nacos as service configuration center

(1) Nacos as configuration center - basic configuration

pom dependency

<dependencies>
    <!--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>
    <!--web + actuator-->
    <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>
    <!--General basic configuration-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </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>

YML configuration

Nacos is the same as spring cloud config. During project initialization, it is necessary to pull the configuration from the configuration center. After pulling the configuration, the project can be started normally.
There is a priority order for loading configuration files in spring boot, and bootstrap is higher than application

bootstrap

server:
  port: 3377

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

application

spring:
  profiles:
    active: dev

Main start

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

Business class

ConfigClientController

@RestController
@RefreshScope
public class ConfigClientController
{
    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/config/info")
    public String getConfigInfo() {
        return configInfo;
    }
}

Automatic refresh of configuration through @ RefreshScope

(2) Add configuration information to Nacos

The matching rule theory in Nacos, the composition format of the dataid in Nacos and the matching rules in the SpringBoot configuration file

Actual operation

Set DataId

Formula: s p r i n g . a p p l i c a t i o n . n a m e − {spring.application.name}- spring.application.name−{spring.profile.active}.${spring.cloud.nacos.config.file-extension}
prefix defaults to spring application. Value of name
spring.profile.active is the profile corresponding to the current environment, which can be configured through the configuration item spring profile. Active to configure
File exception is the data format of the configuration content, which can be configured through the configuration item spring cloud. nacos. config. File extension configuration

summary

(3) Testing

Before startup, check whether there is a corresponding yaml configuration file under the column of Nacos client - Configuration Management - configuration management, run the main startup class of cloud-config-nacos-client3377, and call the interface to view the configuration information, http://localhost:3377/config/info

Built in dynamic refresh: built in dynamic refresh

6, Nacos as configuration center - classified configuration

configuration management

Namespace


(1) 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

(2) Group scheme

Environment differentiation is realized through Group, and a new Group is created

Create a new profile DataID on the nacos graphical interface console

bootstrap+application, add a group configuration under config. Configurable as DEV_GROUP or TEST_GROUP

(3) 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

YML
bootstrap: namespace:

Topics: Spring Cloud Microservices eureka