Spring Cloud Alibaba Nacos service registration and configuration center

Posted by rbama on Sat, 12 Feb 2022 12:59:32 +0100

As the Spring Cloud Netflix project enters the maintenance mode (putting the module in the maintenance mode means that the Spring Cloud team will not add new functions to the module, but will only fix block level bug s and security problems), Alibaba team provides us with a new one-stop solution for microservice development

See official introduction for details: https://github.com/alibaba/spring-cloud-alibaba/blob/master/README-zh.md

1, Nacos overview

What is Nacos?

  • Nacos (Dynamic Naming and Configuration Service): a dynamic service discovery, configuration management and service management center that is easier to build cloud native applications. We can understand it as: Nacos = service registration center + configuration center; Equivalent to Nacos = Eureka + Spring Cloud Config + Spring Cloud Bus

  • Nacos can replace Eureka to implement the service registry, Spring Cloud Config to implement the service configuration center, and Spring Cloud Bus to implement the configured global broadcast. Nacos is a registration center and configuration center that supports the concept of "service governance, service precipitation, sharing and sustainable development" in the primary era of cloud adjustment. (attachment: Nacos official website)

Comparison of registries:

Installation and operation of Nacos:

  • Download address: https://github.com/alibaba/nacos/releases

  • After downloading and decompressing, open the bin directory and double-click startup CMD can be started

  • Enter localhost:8848/nacos in the browser address bar to log in. The default user name and password are nacos. The main page is as follows:

2, Nacos as registry

Project structure:

2.1 Nacos based service providers

1. Build a moudle as the server cloudalibaba provider payment9001

2. Introduce dependency

  • Spring cloud Alibaba dependency introduced by 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>
    
  • The current module pom introduces the Nacos discovery dependency

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

3,applicaiton.yml file configuration

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Configure Nacos address
# Monitoring needs to expose all this
management:
  endpoints:
    web:
      exposure:
        include: '*'

4. The @ EnableDiscoveryClient annotation is required for the main startup class

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

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

}

6. Testing

  • Unlike eureka, you need to write a registry micro service. You can install and open nacos directly.

  • Start the service module and enter the Nacos console. In service management → service list, you can see that the service name Nacos payment provider defined by us has been successfully registered in the Nacos registry.

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

7. Create a new module 9002 with the same configuration

Take another cloudalibaba provider payment9002 module as the server, cluster it with 9001, provide external services in the form of cluster, and register it in Nacos.

2.2 Nacos based service consumers

Nacos supports load balancing by default:

  • When Eureka is used, the service call is based on Ribbon's RestTemplate + @LoadBalance or feign. Feign integrated Ribbon supports load balancing by default. Our Nacos also integrates Ribbon and supports load balancing by default.

1. Create a new module as a service consumer cloudalibaba-consumer-nacos-order83

2. Introducing Nacos discovery dependency

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

3,applicaiton.yml file configuration

server:
  port: 83

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

# The name of the micro service that the consumer will visit (the micro service provider that has successfully registered into nacos)
service-url:
  nacos-user-service: http://nacos-payment-provider

4. The @ EnableDiscoveryClient annotation is required for the main startup class

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

5. Business class

@Configuration
public class ApplicationContextBean {

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

}
@RestController
public class OrderNacosController {

    @Resource
    private RestTemplate restTemplate;

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

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

}

6. Testing

  • Start 9001, 9002, 83

  • Test link: http://localhost:83/consumer/payment/nacos/1 , it is found that 9001 and 9002 appear alternately, that is, polling load balancing

2.3 comparison of Nacos with other registries

Nacos can switch between CP and AP:

  • C consistency A high availability P fault tolerance. reference resources: CAP principle , the mainstream uses AP mode to ensure the high availability of the system.

When to choose which mode to use?

  • AP:

    Generally speaking, if there is no need to store service level information, and the service instance is registered through Nacos client 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.

  • CP:

    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.

Nacos cluster supports AP principle in CAP principle by default, but it can also be switched to CP principle. The switching command is as follows:

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

3, Nacos as configuration center

Nacos can be used as the service configuration center instead of Config + Bus. Attachment: Official document of Nacos service configuration center . Nacos is used as the service configuration center, which is divided into basic configuration (simple use) and classified configuration (multiple environments use dev, test, prod and other environments). Next, we will introduce Nacos as a service configuration center.

3.1 basic configuration of Nacos

1. Create a new module cloudalibaba config Nacos client3377 as the configuration center and register it in Nacos

2. pom introduces Nacos config dependency

<!--introduce nacos-config to configure-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--Register to Nacos,Need to introduce nacos-discovery to configure-->
<!--introduce nacos-discovery to configure-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

3. Configure yml

You need to configure bootstrap YML and application YML two files.

Reason: Nacos is the same as springcloud 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. The loading of configuration files in springboot has priority order, and bootstrap has priority over application. bootstrap.yml is used as a system level resource configuration item, application YML is a user level resource configuration item. In the project, the cooperation between the two takes effect together, bootstrap YML higher priority

  • bootstrap.yml

    # 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 configuration center address
            file-extension: yaml #Specifies the configuration of yaml format
    
    # ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
    # nacos-config-client-dev.yaml
    
  • application.yml

    spring:
      profiles:
        active: dev # Represents the development environment
    

4. Main startup class, add @ EnableDiscoveryClient annotation

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

5. Add @ RefreshScope to the business class to automatically update the configuration

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

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

6. Add configuration item to Nacos

Enter Nacos → configuration management → configuration list → + to add configuration items. The Data ID is written according to the rules.

Data ID naming rules:

Official website: https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html

The complete format of dataId is as follows:

${prefix}-${spring.profile.active}.${file-extension}
  • prefix defaults to spring application. You can also configure the value of the item name.spring cloud. nacos. config. prefix to configure.
  • spring.profile.active is the profile corresponding to the current environment. Note: when spring profile. When active is empty, the corresponding connector - will not exist, and the splicing format of dataId will become ${prefix}$ There may be some unexpected problems with the extension. Spring} (don't leave it blank)
  • File exception is the data format of the configuration content, which can be configured through the configuration item spring cloud. nacos. config. File extension. Currently, only properties and yaml types are supported.

7, Testing

Pass http://localhost:3377/config/info Through the test, it is found that the configuration information of Nacos configuration center can be obtained correctly.

Built in dynamic refresh: modify the yaml configuration file in nacos, call again to view the configuration, and find that the configuration has been refreshed

3.2 Nacos classification configuration

In project development, we will encounter multi environment and multi project management problems. When encountering the following problems, it is obvious that the basic configuration of Nacos cannot solve these problems. Next, let's understand the concepts related to Nacos namespace and Group.

3.2.1 description of naming rules of Nacos

Nacos naming consists of Namespace, group and instance ID. The outermost Namespace is used to distinguish the deployment environment; Group and Data ID are logically used to distinguish two target objects.

By default: Namespace = public, Group = DEFAULT_GROUP,Cluster=DEFAULT

  • Namespace is mainly used to realize isolation. The default namespace of Nacos is public. For example, we now have three environments: development, testing and production. We can create three namespaces. Different namespaces are isolated;

  • Group is a set of configuration sets and one of the dimensions of organization configuration. The default is DEFAULT_GROUP. Configuration sets are grouped by a meaningful name to distinguish configuration sets with the same Data ID. Common scenarios of configuration grouping: if different applications or components use the same configuration type, different microservices can be divided into the same group to solve problem 2; Such as database_url configuration and MQ_topic configuration.

  • Service microservices; A service can contain multiple clusters. The DEFAULT Cluster of Nacos is DEFAULT, and the Cluster is a virtual partition of the specified micro service. For example, for disaster recovery, the service microservices are deployed in Hangzhou computer room and Guangzhou computer room respectively. This can give the service microservices in Hangzhou computer room a Cluster name (HZ) and the service microservices in Guangzhou computer room a Cluster name (GZ). It can also try to make the microservices in the same computer room call each other to improve performance.

  • Instance s are micro service instances.

3.2.2 DataID scheme

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

    The namespace here is the default public, and the Group is also the default.

  • Through spring profile. The active attribute can read configuration files in multiple environments

  • Restart 3377 test http://localhost:3377/config/info , successfully read config. Under test configuration info

3.2.3 Group scheme

  • The default group is DEFAULT_GROUP, now realize the environment partition through group

1. Create a new configuration file and add it to DEV_GROUP grouping

2. Create a new configuration file and add it to TEST_GROUP grouping

3. Add a group configuration under config. Configurable as DEV_GROUP or TEST_GROUP

4. Test:

3.2.4 namescape scheme

1. Create a Namesapce for dev/test

  • Different namespaces can be seen in the service list

2. Create three different grouped profiles in the two newly created namespace s

3. Modify the yml file of 3377

  • bootstrap:

  • application:

4. Testing

  • dev namesapce:

  • test namesapce:

4, Nacos cluster construction and persistence configuration (to be supplemented)

Reference blog: Nacos cluster construction and persistence configuration (Linux)

Topics: Spring Cloud Nacos