Micro service series: Nacos registry of Spring Cloud Alibaba

Follow the previous article Micro service series: service gateway Spring Cloud Gateway integration Sentinel current limiting - Nuggets (juejin.cn) After completing the basic study of Spring Cloud Gateway, starting from this article, we enter the study of Nacos.

Nacos is a dynamic service discovery, configuration management and service management platform that is easier to build cloud native applications. It is the combination of registration center and configuration center.

Equivalent to:

Nacos = Eureka + Config + Bus

Today we are learning about the function of Nacos as a registry

Don't say much, start today's study.

Basic introduction

  • What is a registry

The registry plays a very important role in the micro service project. It is the link in the micro service architecture. Similar to the address book, it records the mapping relationship between the service and the service address. In the distributed architecture, services will be registered here. When a service needs to call other services, it will find the address of the service here and call it.

  • Why use a registry

The registry solves the problem of service discovery. When there is no registry, the inter service call needs to know the address or proxy address of the called party. When the service changes the deployment address, it has to modify the address specified in the call or modify the proxy configuration. With the registry, each service only needs to know the service name when calling others, and the continuation address will be synchronized through the registry.

  • Nacos registry

Nacos is an open-source dynamic service discovery, configuration management and service management platform of Alibaba that is easier to build cloud native applications.

Nacos has the following characteristics:

  1. Service discovery and service health monitoring: support DNS based and RPC based service discovery, support real-time health inspection of services, and prevent sending requests to unhealthy hosts or service instances;
  2. Dynamic configuration service: dynamic configuration service allows you to manage the application configuration and service configuration of all environments in a centralized, external and dynamic way;
  3. Dynamic DNS Service: the dynamic DNS service supports weighted routing, making it easier for you to realize middle tier load balancing, more flexible routing strategy, traffic control and simple DNS resolution service in the intranet of the data center;
  4. Service and metadata management: support the management of all services and metadata in the data center from the perspective of micro service platform construction.

Official documents: https://nacos.io/zh-cn/docs/what-is-nacos.html

Download start

Here we choose to start Nacos under the Windows system of our computer

1. Download the installation package

Can from https://github.com/alibaba/nacos/releases Download Nacos server - $version Zip package.

In addition to the installation package download, there is also the source code download. See the official documentation for details.

2. Command start

After Windows Downloads and decompresses (. zip),
The startup command is as follows (standalone stands for stand-alone mode, non cluster mode):

startup.cmd -m standalone

Nacos is in cluster MODE by default. You can set startup CMD attribute MODE is stand-alone MODE:

set MODE="standalone"

3. Open the console

After the previous step is started successfully, we can access http://localhost:8848/nacos/index.html Enter the visualization console page.
The default user name and password are both nacos.

How to use

1. Add dependency

<!-- 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>

Note: version 2.1.x.RELEASE The corresponding is spring boot 2.1 X version. edition 2.0.x.RELEASE The corresponding is spring boot 2.0 X version, version 1.5.x.RELEASE The corresponding is spring boot 1.5 X version.

For more version correspondence References: Version Description Wiki

2. Add Nacos configuration

server:
  port: 9201

# Spring
spring:
  application:
    # apply name
    name: cloud-nacos-provider
  cloud:
    nacos:
      discovery:
        # Service registration address
        server-addr: 127.0.0.1:8848

3. @EnableDiscoveryClient enables 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;
        }
    }
}

@EnableDiscoveryClient is the native annotation of Spring Cloud. It is not necessary to add this annotation in the higher version. The service registration is automatically opened by default.

It is observed that there is also a test interface, browser access http://localhost:9201/echo/ezhang try:

4. Start the service and observe the list of Nacos console services

Our service provider successfully registered.

Test verification

In the previous step, we have configured the service provider. Next, we configure a service consumer and enable the service consumer to obtain the service it wants to call from the Nacos server through the service registration and discovery function of Nacos.

Create a new project cloud Nacos consumer. The configuration steps are the same as those of the service provider.

1. application.yml file

server:
  port: 9202

# Spring
spring:
  application:
    # apply name
    name: cloud-nacos-consumer
  cloud:
    nacos:
      discovery:
        # Service registration address
        server-addr: 127.0.0.1:8848

2. NacosConsumerApplication.java file

@SpringBootApplication
public class NacosConsumerApplication {

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

    // Add a restTemplate object injection method. Note that the @ LoadBalanced annotation must be added here, otherwise it cannot be called remotely
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        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);
        }
    }

}

to RestTemplate Add @ LoadBalanced annotation to the instance to enable @ LoadBalanced and Ribbon Integration of:

3. Start the project

Observe the Nacos console service list and find that it has been successfully registered

4. Access address http://localhost:9202/test/ezhang

The test passed.

load balancing

1. Why does Nacos support load balancing?

Observe the Nacos discovery package and find that ribbon is integrated in it.

2. Test and verify the load balancing of Nacos.

(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:
    # apply name
    name: cloud-nacos-provider
  cloud:
    nacos:
      discovery:
        # Service registration address
        server-addr: 127.0.0.1:8848

(2) Change the NacosProviderCopyApplication and NacosProviderApplication

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

(3) Start the project and observe the console

You can see that there are two service providers and one service consumer. Click the service provider details to see that there is no problem with the two instances.

(4) Service consumer code remains unchanged, browser access http://localhost:9202/test/ezhang

Polling OK

Comparison of mainstream service registries

Comparison itemsNacosEurekaConsulZookeeper
Consistency protocolSupport AP and CP modelsAP modelCP modelCP model
health examinationTCP/HTTP/MYSQL/Client BeatClient BeatTCP/HTTP/gRPC/CmdKeep Alive
Load balancing strategyWeight / metadata/SelectorRibbonFabio-
Avalanche protectionhavehavenothingnothing
Auto logoff instancesupportsupportI won't support itsupport
access protocolHTTP/DNSHTTPHTTP/DNSTCP
Monitoring supportsupportsupportsupportsupport
Multi data centersupportsupportsupportI won't support it
Cross registry synchronizationsupportI won't support itsupportI won't support it
Spring cloud integrationsupportsupportsupportI won't support it
Dubbo integrationsupportI won't support itI won't support itsupport
k8s integrationsupportI won't support itsupportI won't support it

From the above comparison, we can see that as a service discovery center, Nacos has more functional support items. In the long run, Nacos will support the combination of spring cloud + kubernetes in future versions to fill the gap between the two. The same set of service discovery and configuration management solutions can be adopted under the two systems, which will greatly simplify the cost of use and maintenance. In addition, Nacos plans to implement Service Mesh, which is also the development trend of micro services in the future.

Nacos supports switching between AP and CP modes

C means 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 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 service availability. 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.

supplement

Source code address of this article: https://gitee.com/zhang33565417/cloud-alibaba

PS: I've seen it here. Give it a compliment, Yanzu!

Keywords: Java Spring Cloud Microservices Nacos

Added by manohoo on Wed, 19 Jan 2022 03:13:55 +0200