This is the first day of my participation in the First Challenge 2022

Following on from the previous micro services series: After completing the basic learning of Spring Cloud Gateway, starting from this article, we will enter into the learning of Nacos.

Nacos is a dynamic service discovery, configuration management, and service management platform that makes it easier to build cloud-native applications. The combination of registry and configuration center.

Is equivalent to:

Nacos = Eureka + Config + Bus

Today we will learn about Nacos’s functions as a registry

Without further ado, let’s begin today’s lesson.

Basic introduction

  • What is a registry

Registries play a very important role in microservice projects. They are the link in the microservice architecture, similar to the address book, which records the mapping between services and service addresses. In a distributed architecture, services are registered here, and when a service needs to call another service, it finds the address of the service and makes the call.

  • Why use a registry

The registry addresses service discovery issues. In the absence of a registry, inter-service calls need to know the address of the called party or the proxy address. When a service changes its deployment address, it has to change the address specified in the call or change the proxy configuration. With the registry, each service only needs to know the service name when calling others, and the address will be synchronized through the registry.

  • Nacos Registry

Nacos is alibaba’s open source platform for dynamic service discovery, configuration management and service management, which is easier to build cloud native applications.

Nacos has the following features:

  1. Service discovery and service health monitoring: support DNS and RPC-based service discovery, support real-time health check of services, prevent requests to unhealthy hosts or service instances;
  2. Dynamically configured services: Dynamically configured services allow you to manage application and service configurations for all environments in a centralized, external, and dynamic manner.
  3. Dynamic DNS service: The dynamic DNS service supports weighted routing, enabling you to implement load balancing at the middle layer, flexible routing policies, traffic control, and simple DNS resolution services on the data center Intranet.
  4. Services and metadata management: Support the management of all services and metadata in the data center from the perspective of micro-service platform construction.

IO/zh-CN /docs/…

Download to start the

Here we chose to start Nacos on our computer’s Windows system.

1. Download the installation package

Can download it from https://github.com/alibaba/nacos/releases nacos – server – $version. Zip bags.

In addition to the installation package download and source download, see the official documentation.

2. Start the command

After extracting the Windows download (.zip), the startup command is as follows (standalone stands for standalone mode, not cluster mode) :

startup.cmd -m standalone
Copy the code

The default Nacos is cluster MODE. The startup. CMD property can be set to standalone MODE.

set MODE="standalone"
Copy the code

3. Open the console

Start step after success, we can visit http://localhost:8848/nacos/index.html to enter visualization console page. The default username and password are both nacos.

How to use

1. Add dependencies

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

<! -- SpringBoot Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

Note: Version 2.1.X. lease corresponds to Spring Boot version 2.1.x. Release corresponds to Spring Boot 2.2. x, and 1.5.x. release corresponds to Spring Boot 1.5.x.

For more version mappings, see version Description Wiki

2. Add the Nacos configuration

server:
  port: 9201

# Spring
spring:
  application:
    # app name
    name: cloud-nacos-provider
  cloud:
    nacos:
      discovery:
        # service registered address
        server-addr: 127.0. 01.: 8848
Copy the code

3. @EnableDiscoveryClientEnable the service registration discovery function

@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosProviderApplication.class, args);
    }

    @RestController
    class EchoController {
        @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
        public String echo(@PathVariable String string) {
            return "Hello Nacos Discovery "+ string; }}}Copy the code

@enableDiscoveryClient is a native annotation of Spring Cloud. In later versions, you do not need to add this annotation. Service registration is automatically enabled by default.

Observed that there is a test interface, try browser to http://localhost:9201/echo/ezhang:

4. Start the service and observeNacosConsole Service List

Our service provider was successfully registered.

The validation test

We configured the service provider in the previous step. Next, we configure a service consumer and make it possible for the service consumer to get the service it wants to invoke from Nacos Server through Nacos’s service registry discovery feature.

Create a new project, Cloud-Nacos-Consumer, with the same configuration steps as the service provider.

1. application.ymlfile

server:
  port: 9202

# Spring
spring:
  application:
    # app name
    name: cloud-nacos-consumer
  cloud:
    nacos:
      discovery:
        # service registered address
        server-addr: 127.0. 01.: 8848
Copy the code

2. NacosConsumerApplication.javafile

@SpringBootApplication
public class NacosConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerApplication.class, args);
    }

    // Add a new restTemplate object injection method. Note that the @loadBalanced annotation must be added here, otherwise it cannot be called remotely
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(a) {
        return new RestTemplate();
    }

    @RestController
    public class TestController {

        private final RestTemplate restTemplate;

        @Autowired
        public TestController(RestTemplate restTemplate) {this.restTemplate = restTemplate; }@RequestMapping(value = "/test/{str}", method = RequestMethod.GET)
        public String echo(@PathVariable String str) {
            return restTemplate.getForObject("http://cloud-nacos-provider/echo/"+ str, String.class); }}}Copy the code

Add @loadBalanced to the RestTemplate instance to enable @loadBalanced integration with the Ribbon:

3. Start the project

Look at the list of Nacos console services and see that they have been successfully registered

4. Access addresshttp://localhost:9202/test/ezhang

Test passed.

Load balancing

1. WhyNacosLoad balancing?

Look at the Nacos-Discovery package and see that it integrates the ribbon.

2. Test and verifyNacosLoad balancing of.

(1) First, copy the above cloud-nacos-provider sub-module to a cloud-nacos-provider-copy, and change the port number to 9211

server:
  port: 9211

# Spring
spring:
  application:
    # app name
    name: cloud-nacos-provider
  cloud:
    nacos:
      discovery:
        # service registered address
        server-addr: 127.0. 01.: 8848
Copy the code

The change NacosProviderCopyApplication and NacosProviderApplication (2)

@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderCopyApplication {

    @Value("${server.port}")
    private String serverProt;

    public static void main(String[] args) {
        SpringApplication.run(NacosProviderCopyApplication.class, args);
    }

    @RestController
    class EchoController {
        @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
        public String echo(@PathVariable String string) {
            return "Hello Nacos Discovery "+ serverProt + string; }}}Copy the code

(3) Start the project and observe the console

You can see that there are two service providers and one service consumer, click on service provider details and see that there is no problem with both instances.

(4) the service consumer code remains the same, the browser to http://localhost:9202/test/ezhang

Polling is OK

Mainstream service registry comparison

Compare the project Nacos Eureka Consul Zookeeper
Consistency protocol AP and CP models are supported AP model CP model CP model
Health check TCP/HTTP/MYSQL/Client Beat Client Beat TCP/HTTP/gRPC/Cmd Keep Alive
Load Balancing Policy Weight/metadata/Selector Ribbon Fabio
Avalanche protection There are There are There is no There is no
Automatic logout instance support support Does not support support
Access protocol HTTP/DNS HTTP HTTP/DNS TCP
Listening to the support support support support support
Multi-data center support support support Does not support
Synchronization across registries support Does not support support Does not support
SpringCloud integration support support support Does not support
Dubbo integration support Does not support Does not support support
K8s integration support Does not support support Does not support

From the above comparison, we can see that Nacos, as a service discovery center, has more functional support items, and in the long run, Nacos will support the combination of SpringCLoud+Kubernetes in the future version, filling the gap between the two. The same service discovery and configuration management solution can be adopted in both systems, which greatly simplifies the cost of use and maintenance. In addition, Nacos plans to implement Service Mesh, which is also the future trend of microservices development.

Nacos supports switching between AP and CP modes

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

When to choose which mode to use?

Generally speaking, the AP mode can be selected if the service instance does not need to store service level information and is registered with NACOS-Client and can keep heartbeat reporting. Current mainstream services, such as Spring Cloud and Dubbo services, are applicable to AP mode. AP mode reduces consistency for service availability, so only temporary instances can be registered in AP mode.

CP is required if configuration information needs to be edited or stored at the service level, and the K8S service and DNS service are suitable for CP mode. In CP mode, persistent instances can be registered and Raft protocol is used as the cluster mode. In this mode, services must be registered before instances are registered. If the service does not exist, an error is returned.

supplement

This article source address: gitee.com/zhang335654…

PS: Now that you’ve seen it, give it a thumbs up, Daniel!