Hello everyone, I am Nai nai ~

This week, we signed up to Nacos as a worker node.

This article provides the complete code sample, see github.com/YunaiV/Spri… Labx-01-spring-cloud-alibaba-nacos-discovery directory.

Original is not easy, to point a Star hey, together blunt duck!

1. An overview of the

In this paper, we will learn the Spring Cloud Alibaba Nacos Discovery component provided by Spring Cloud Alibaba. Based on the programming model of Spring Cloud, access Nacos as the registry. Implement registration and discovery of services.

Service registration/Discovery: Nacos Discovery

Service discovery is one of the most critical components in microservices architecture. It would be very difficult to manually configure the service list of all service providers for each client, and it would be difficult to dynamically scale the service.

Nacos Discovery helps you automatically register your services with the Nacos server and dynamically sense and refresh the list of services for a service instance.

In addition, Nacos Discovery registers some metadata information about the service instance itself – such as host, port, health check URL, home page, and so on – with Nacos.

Before starting this article, you need to learn a little bit about Nacos. Read the introduction to Nacos Minimalism article, read the first and second sections, and build a Nacos service on your machine.

2. Principle of the registry

Before we start building an example of Nacos Discovery, let’s take a quick look at how the registry works.

When using a Registry, there are three roles: Service Provider, Service Consumer, and Registry.

In some articles, the service provider is called Server and the service consumer is called Client. Fat friends know.

The interaction of the three roles is shown below:

(1) the Provider:

  • At startup, register yourself with Registry as an Instance of a Service.
  • At the same time, periodically send a heartbeat to Registry to tell you that you are alive.
  • When closed, unregister with Registry.

(2) the Consumer:

  • At startup, the used services are subscribed to Registry and the list of instances of the services is cached in memory.
  • Later, when the Consumer invokes the Provider of the corresponding service, it selects one from the memory list of instances of the service and makes the remote invocation.
  • When closed, unsubscribe from Registry.

(3) the Registry:

  • If the Provider has no heartbeat for a period of time, it is removed from the service instance list.
  • Consumers that subscribe to the service are notified when the list of instances of the service changes (new or removed) so that the Consumer can flush the local cache.

Of course, different registries may have slightly different implementation principles. The Eureka registry, for example, does not provide notification, but the Eureka Client polls itself periodically to update the local cache.

In addition, Provider and Consumer are roles defined. A service can be both Provider and Consumer. For example, a coupon service can provide an interface to an order service and invoke an interface provided by a user service.

3. Quick start

The sample code corresponds to the repository:

  • Service provider: LabX-01-SCA-NACos-discovery-Demo01-provider
  • Service consumer: LabX-01-SCA-NACos-discovery-Demo01-consumer

In this section, we build a quick start example of the Nacos Discovery component. The steps are as follows:

  • First, set up a service providerdemo-providerRegister the service into Nacos.
  • Then, build a service consumerdemo-consumer, obtained from Nacosdemo-providerA list of instances of the service, select one of the examples, to make an HTTP remote call.

3.1 Setting up service providers

createlabx-01-sca-nacos-discovery-demo01-providerProjects, as service providersdemo-provider. The final project code is shown in the figure below:

3.1.1 Introducing dependencies

In the POM.xml file, Spring Cloud Nacos Discovery dependencies are mainly introduced. The code is as follows:


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>labx-01</artifactId>
        <groupId>cn.iocoder.springboot.labs</groupId>
        <version>1.0 the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>labx-01-sca-nacos-discovery-demo01-provider</artifactId>

    <properties>
        <spring.boot.version>2.2.4. RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR1</spring.cloud.version>
        <spring.cloud.alibaba.version>2.2.0. RELEASE</spring.cloud.alibaba.version>
    </properties>

    <! -- Introduce Spring Boot, Spring Cloud and Spring Cloud Alibaba BOM files to manage dependent versions and prevent incompatibility. In the https://dwz.cn/mcLIfNKt article, the Spring Cloud Alibaba development team recommends the three dependencies -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-parent</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring.cloud.alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <! Import SpringMVC dependencies and configure them automatically.
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <! -- Introducing Spring Cloud Alibaba Nacos Discovery dependencies, using Nacos as the registry and realizing automatic configuration of it -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

</project>
Copy the code

Friendly reminder: a little too long, don’t panic ~

In
, we introduce Spring Boot, Spring Cloud and Spring Cloud Alibaba BOM files to manage the dependent versions and avoid incompatibility. The dependencies of all three are recommended in the Spring Cloud Official Documentation – Release Notes. The following table:

Spring Cloud Version Spring Cloud Alibaba Version Spring Boot Version
Spring Cloud Greenwich 2.1.1. RELEASE 2.1. X.R ELEASE
Spring Cloud Finchley 2.0.1. RELEASE 2.0. X.R ELEASE
Spring Cloud Edgware 1.5.1. RELEASE 1.5. X.R ELEASE
  • Here, we choose the Spring Cloud Alibaba version as2.2.0. RELEASE.
  • Under the current version, the Nacos version we use is1.1.4.

The spring-cloud-starter-Alibaba-nacos-Discovery dependency is introduced, nacOS is used as the registry, and its automatic configuration is realized.

3.1.2 Configuration Files

Create the application.yaml profile and add the Nacos Discovery configuration item. The configuration is as follows:

spring:
  application:
    name: demo-provider # Spring application name
  cloud:
    nacos:
      Nacos as the configuration item of the registry corresponds to the NacosDiscoveryProperties configuration class
      discovery:
        server-addr: 127.0. 01.: 8848 # Nacos server address
        service: ${spring.application.name} Service name registered to Nacos. The default value is ${spring.application.name}.

server:
  port: 18080 # Server port. The default value is 8080
Copy the code

Focus on spring. Cloud. Nacos. Discovery configuration items, it is nacos discovery configuration items prefix, corresponding NacosDiscoveryProperties configuration items.

3.1.3 DemoProviderApplication

Create the DemoProviderApplication class, create the application launch class, and provide the HTTP interface. The code is as follows:

@SpringBootApplication
@EnableDiscoveryClient
public class DemoProviderApplication {

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

    @RestController
    static class TestController {

        @GetMapping("/echo")
        public String echo(String name) {
            return "provider:"+ name; }}}Copy the code

① The @SpringBootApplication annotation, added to the class, declares that this is a SpringBoot application. Spring Cloud is built on top of Spring Boot, so it needs to be added.

② @enableDiscoveryClient annotation to enable the registration and discovery function of Spring Cloud. However, starting with the Spring Cloud Edgware version, the @enableDiscoveryClient annotation is no longer required, just the introduction of the Spring Cloud registration discovery component will automatically enable the registration discovery function. For example, we have already introduced the Spring-cloud-starter-Alibaba-nacos-Discovery dependency, so there is no need to add the @enableDiscoveryClient annotation.

In the Spring Cloud Common project, the DiscoveryClient interface is defined as a generic DiscoveryClient that provides API methods for reading services and reading lists of services. Components that want to be integrated into the registry of the Spring Cloud architecture need to provide the corresponding DiscoveryClient implementation class.

For example, Spring Cloud Alibaba NacosDiscovery provides the NacosDiscoveryClient implementation, Spring Cloud Netflix Eureka provides the EurekaDiscoveryClient implementation.

In this way, you only need to obtain the DiscoveryClient instead of the implementation to ensure its universality.

Provider :${name} provider:${name}

3.1.4 Simple test

① Start the service provider through DemoProviderApplication, IDEA console outputs logs as follows:

/ /... Omit other logs
2020-02- 0815:25:57.406  INFO 27805 --- [           main] c.a.c.n.registry.NacosServiceRegistry    : nacos registry, DEFAULT_GROUP demo-provider 10.1711.115.:18080 register finished
Copy the code
  • servicedemo-providerLog registered to Nacos.

② Open the Nacos console, and you can see the services in the service listdemo-provider. The diagram below:

3.2 Setting up service consumers

createlabx-01-sca-nacos-discovery-demo01-consumerProjects, as service providersdemo-consumer. The final project code is shown in the figure below:

The entire project code, and the service provider is basically the same, after all, is the sample code 😜

3.2.1 Importing Dependencies

As in “3.1.1 Introducing dependencies”, just modify Maven
to labX-01-SCA-nacos-discovery-demo01-consumer, see the pop.xml file.

3.2.2 Configuration File

Create the application.yaml configuration file and add the corresponding configuration items. The configuration is as follows:

spring:
  application:
    name: demo-consumer # Spring application name
  cloud:
    nacos:
      Nacos as the configuration item of the registry corresponds to the NacosDiscoveryProperties configuration class
      discovery:
        server-addr: 127.0. 01.: 8848 # Nacos server address

server:
  port: 28080 # Server port. The default value is 8080
Copy the code

The configuration project spring.application.name is changed to demo-consumer, which is basically the same as that in 3.1.2 Configuration File.

3.2.3 DemoConsumerApplication

Create the DemoConsumerApplication class, create the application launch class, and provide an HTTP interface to invoke the service provider. The code is as follows:

@SpringBootApplication
// @EnableDiscoveryClient
public class DemoConsumerApplication {

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

    @Configuration
    public class RestTemplateConfiguration {

        @Bean
        public RestTemplate restTemplate(a) {
            return newRestTemplate(); }}@RestController
    static class TestController {

        @Autowired
        private DiscoveryClient discoveryClient;
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private LoadBalancerClient loadBalancerClient;

        @GetMapping("/hello")
        public String hello(String name) {
            // <1> Get an instance of the service 'demo-provider'
            ServiceInstance instance;
            if (true) {
                // Get the list of instances corresponding to the service 'demo-provider'
                List<ServiceInstance> instances = discoveryClient.getInstances("demo-provider");
                // Select the first one
                instance = instances.size() > 0 ? instances.get(0) : null;
            } else {
                instance = loadBalancerClient.choose("demo-provider");
            }
            // <2> Initiate the call
            if (instance == null) {
                throw new IllegalStateException("No instance obtained");
            }
            String targetUrl = instance.getUri() + "/echo? name=" + name;
            String response = restTemplate.getForObject(targetUrl, String.class);
            // Return the result
            return "consumer:"+ response; }}}Copy the code

The @enableDiscoveryClient annotation is no longer needed, so we annotate it for the reasons explained above.

(2) RestTemplateConfiguration configuration class, create RestTemplate Bean. RestTemplate is a Spring-provided HTTP call template utility class that makes it easy to call the service provider’s HTTP API later.

③ TestController provides the/Hello interface for invoking the service provider’s/Demo interface. It’s a little bit of code, so let’s explain it a little bit.

DiscoveryClient property, discoveryClient object, service discoveryClient, which we’ve already introduced. What we inject here is not the NacosDiscoveryClient provided by NacosDiscovery to ensure universality. If we use Eureka or Zookeeper instead of Nacos as the registry in the future, we won’t need to change the code here.

LoadBalancerClient property, loadBalancerClient object, load balancing client. We’ll use it later, selecting one from the list of instances of the service Demo-Provider obtained by Nacos to make the HTTP call.

In the Spring Cloud Common project, the LoadBalancerClient interface is defined. As a general load balancing client, it provides API methods such as selecting an instance from a specified service and making a request to the specified service. Components that want to integrate load balancing into the Spring Cloud architecture need to provide the corresponding LoadBalancerClient implementation class.

For example, the Spring Cloud Netflix Ribbon provides the RibbonLoadBalancerClient implementation.

In this way, you only need to obtain the DiscoveryClient instead of the implementation to ensure its universality. 😈 However, it seems that the Ribbon is currently the only load-balancing component in the Spring Cloud system.

Of course, the list of service instances of LoadBalancerClient is provided by DiscoveryClient.

The/Hello interface, a sample interface, makes an HTTP call to the service provider.

  • < 1 >To obtain servicedemo-providerAn instance of. Here we provide code in two ways, based on DiscoveryClient and LoadBalancerClient.
  • < 2 >, concatenates the destination URL of the request using the ServiceInstance object, and then initiates the HTTP call using the RestTemplate.

3.2.4 Simple test

① Start the service consumer through DemoConsumerApplication, IDEA console outputs logs as follows:

/ /... Omit other logs
2020-02- 0818:05:35.810  INFO 35047 --- [           main] c.a.c.n.registry.NacosServiceRegistry    : nacos registry, DEFAULT_GROUP demo-consumer 10.1711.115.:28080 register finished
Copy the code
  • servicedemo-consumerLog registered to Nacos.

Note that service consumers and service providers are roles that are essentially services that can register themselves in a registry.

② Open the Nacos console, and you can see the services in the service listdemo-consumer. The diagram below:

(3) access to the service consumer http://127.0.0.1:28080/hello? Name = yudaoyuanma interface, return the result for “consumer: the provider: yudaoyuanma”. The invocation of the remote service provider succeeded.

④ Open the Nacos console and you can see the subscription relationship in the subscriber list. The diagram below:

(5) shut down after the service provider, visit http://127.0.0.1:28080/hello? again Name = Yudaoyuanma interface. An error message is displayed indicating that the instance list of the locally cached service Demo-Provider has been refreshed and there is no instance.

😈 we don’t show you how to test multiple service providers, you can try it yourself.

4. Detailed explanation of Nacos concept

Friendship tips: The content of this section is based on the following two documents, and it is recommended that fat friends have a look at it later:

  • Nacos Official Documentation — Concepts
  • Nacos Official Documentation — Architecture

4.1 Data Model

Nacos data model keys are uniquely validated by triples. As shown below:

  • As a registry, Namespace + Group + Service
  • In the configuration center, Namespace + Group + DataId

Let’s look at the concepts of Namespace, Group, and Service.

4.1.1 Namespace Namespace

Used for configuration isolation of tenant granularity. Default is public (public namespace).

Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of Namespace is the isolation of configurations in different environments, such as the isolation of resources (such as configurations and services) between the development test environment and the production environment.

Later in the “6. Multi-environment Configuration” section, we will isolate services for different environments through Namespace.

4.1.2 Group Service Group

Different services can be grouped into the same group. The default is DEFAULT_GROUP (default group).

4.1.3 Service Service

For example, user services, order services, goods services, and so on.

4.2 Service domain model

Service can further refine the Service domain model as shown below:

Let’s look at the concept of each “node” in the diagram.

2 the Instance Instance

A process with an accessible network address (IP:Port) that provides one or more services.

Let’s take the section 3.1 Setting up a service Provider as an example:

  • If we startaJVM processes are servicesdemo-providerUnder theaInstance.
  • If we startmultipleJVM processes are servicesdemo-providerUnder themultipleInstance.

4.2.2 Cluster Cluster

All service instances of a service form a Default cluster. Clusters can be further divided according to requirements and can be divided in virtual clusters.

For example, we deploy services in multiple rooms, each of which can be created as a virtual cluster. When each service registers with Nacos, it sets up the virtual cluster in the machine room. In this way, when a service invokes other services, the service preferentially invokes the service in the equipment room through the virtual cluster. In this way, service availability is improved while performance is ensured.

4.2.3 Metadata Metadata

Nacos Metadata (such as configuration and service) description information, such as service version, weight, disaster recovery policy, load balancing policy, authentication configuration, and various user-defined labels.

From the perspective of scope, it can be divided into service level meta-information, cluster meta-information and instance meta-information. The diagram below:

FROM Dubbo official Documentation — Multiple versions

Take the service version of Nacos metadata as an example. When an interface is implemented and an incompatible upgrade occurs, the version number can be used for transition. Services with different version numbers do not reference each other.

You can follow these steps to perform version migration:

  1. During low-stress periods, upgrade half of the providers to the new version first
  2. Then upgrade all customers to the new version
  3. Then upgrade the remaining half of the providers to the new version

FROM Dubbo official Documentation — Token Validation

The authentication configuration of Nacos metadata is again used as an example. Controlling permissions in the registry to decide whether to issue tokens to consumers through token validation prevents consumers from bypassing the registry to access providers. In addition, the registry provides flexibility to change authorization without changing or upgrading the provider.

4.2.4 Health Check

Checks the health of an instance mounted to a service in a specified manner to determine whether the instance can provide services. Based on the inspection results, the instance is judged to be healthy or unhealthy.

When a resolution request is made to the service, an unhealthy instance is not returned to the client.

Health protection threshold

To prevent too many instances from being unhealthy so that traffic flows all the way to the healthy instance and the traffic pressure collapses the healthy instance and creates an avalanche effect, the health protection threshold should be defined as a floating point number between 0 and 1.

When the proportion of domain name health instances to total service instances is smaller than the value, the domain name is returned to the client regardless of whether the instance is healthy or not. Doing so loses some traffic, but keeps the remaining healthy instances of the cluster working.

4.3 summary

In order to make fat friends better understand, we organize the data model and service domain model as shown in the figure below:

5. More configuration items

In the “3. Quick Start” section, we used only two configuration items Nacos Discovery Starter to get started quickly. In fact, Nacos Discovery Starter provides a lot of configuration items, we refer to the documentation to comb through the configuration items.

Nacos server

Configuration items Key instructions
Server address spring.cloud.nacos.discovery.server-addr Nacos Server starts the LISTENING IP address and port
AccessKey spring.cloud.nacos.discovery.access-key When you want to go to Ali Cloud, ali cloud above a cloud account name
SecretKey spring.cloud.nacos.discovery.secret-key When you want to go on Ali cloud, ali cloud above a cloud account password

Service related

Configuration items Key instructions
The namespace spring.cloud.nacos.discovery.namespace One common scenario is the separation of registration between different environments, such as isolation of resources (such as configurations and services) between development test environments and production environments
Service group spring.cloud.nacos.discovery.group Different services can be grouped into the same group. The default isDEFAULT_GROUP
The service name spring.cloud.nacos.discovery.service Name of the registered service. The default is${spring.application.name}
The cluster spring.cloud.nacos.discovery.cluster-name Nacos Cluster name. The default isDEFAULT
The weight spring.cloud.nacos.discovery.weight The value ranges from 1 to 100. A larger value indicates a larger weight. The default is 1
Metadata spring.cloud.nacos.discovery.metadata Using the Map format, users can customize metadata related to services as required
Whether to enable Nacos Watch spring.cloud.nacos.discovery.watch.enabled Can be set tofalseTo turn off watch. The default istrue

Network related

Configuration items Key instructions
The network card name spring.cloud.nacos.discovery.network-interface If the IP address is not configured, the registered IP address is the IP address of this NIC. If this parameter is not configured, the IP address of the first NIC is used by default
Registered IP address spring.cloud.nacos.discovery.ip Highest priority
Registered port spring.cloud.nacos.discovery.port By default, no configuration is required and automatic detection is performed. The default is- 1

Other related

Configuration items Key instructions
Whether to integrate Ribbon ribbon.nacos.enabled It is generally set totrueCan. The default istrue
Log file name spring.cloud.nacos.discovery.log-name
Access point spring.cloud.nacos.discovery.endpoint An inbound domain name of a service in a region through which you can dynamically obtain the server address

6. Configure multiple environments

The sample code corresponds to the repository:

  • Service provider: LabX-01-SCA-NACos-discovery-Demo02-provider
  • Service consumer: LabX-01-SCA-NACos-discovery-Demo02-consumer

The same service will be deployed to development, test, pre-release, production, etc., so we need to add Nacos configurations for different environments in the project. Typically, the same Nacos is used for development and testing, and another Nacos is used for pre-release and production. So how do we isolate different environments for the same Nacos?

In fact, the Nacos developers have shown us how to do this, through the Nacos Namespace. The documentation is as follows:

FROM Nacos Documentation — Nacos Concept

Namespace for tenant granularity configuration isolation. Different namespaces can have the same Group or Data ID configuration. One of the common scenarios of Namespace is the isolation of configurations in different environments, such as the isolation of resources (such as configurations and services) between the development test environment and the production environment.

Let’s set up an example of a multi-environment configuration. The steps are as follows:

  • First, we will create a Namespace in Nacos for the development environment to usedev, the Namespace used by the test environment isuat.
  • Then, set up a service providerdemo-provider, the use ofThe development ofEnvironment configuration, register services to NacosdevUnder the Namespace.
  • After that, build a service consumerdemo-consumer, invoking the service providerdemo-providerHTTP interface provided.
    • Use the firstThe development ofEnvironment configuration because of servicedemo-provider isIn NacosdevRegister under Namespace, so call itsuccessful.
    • After usingtestEnvironment configuration because of servicedemo-provider Don’tIn NacosuatRegister under Namespace, so call itfailure.

Note: In the Spring Boot (Spring Cloud) project, you can use the Profiles mechanism, based on the spring.profiles. Active configuration item, enabling different environments to read different configuration files.

For those who don’t know, you can look at the “6. Multi-environment Configuration” section of the “Impression Path Spring Boot Configuration File Introduction”.

6.1 Creating the Nacos Namespace

① Open the Namespace menu on the Nacos UI to access the Namespace function. As shown below:

② Click the “New Namespace” button in the upper right corner of the list. The “New Namespace” window is displayed to create a new namespacedevNamespace. Enter the following information and click OK to complete creation. As shown below:

3 Repeat this operation to create another oneuatNamespace. In the enddevuatThe information is shown below:

6.2 Setting up service Providers

Copy the labX-01-SCA-NACos-discovery-Demo02-Provider project from the labX-01-SCA-NACos-Discovery-Demo02-Provider project in section 3.1 setting up a Service Provider. Then modify on it, convenient to build ~

6.2.1 Configuration File

Modify the application.yaml configuration file to remove the Nacos Discovery configuration item and add it to the configuration file of different environments later. The configuration is as follows:

spring:
  application:
    name: demo-provider # Spring application name

server:
  port: 18080 # Server port. The default value is 8080
Copy the code

Create the application-dev.yaml configuration file for the development environment, and add the Nacos Discovery configuration item with Namespace dev as the Namespace. The configuration is as follows:

spring:
  cloud:
    nacos:
      Nacos as the configuration item of the registry corresponds to the NacosDiscoveryProperties configuration class
      discovery:
        server-addr: 127.0. 01.: 8848 # Nacos server address
        namespace: 14226a0d-799f-424d-8905-162f6a8bf409 # Nacos specifies the number of namespace dev
Copy the code

Create the application-uat.yaml configuration file for the test environment, and add the Nacos Discovery configuration item with Namespace as UAT. The configuration is as follows:

spring:
  cloud:
    nacos:
      Nacos as the configuration item of the registry corresponds to the NacosDiscoveryProperties configuration class
      discovery:
        server-addr: 127.0. 01.: 8848 # Nacos server address
        namespace: bc8c8c2d-bd85-42bb-ada3-1a8f940ceb20 # Nacos specifies the number of the uAT namespace
Copy the code

6.2.2 Simple test

Next, we use the command line argument for the –spring.profiles. Active configuration item to implement different environments and read different configuration files.

1) first configuration--spring.profiles.activedev, set DemoProviderApplication to readapplication-dev.yamlConfiguration file. As shown below:

The service provider is then started through DemoProviderApplication.

② Open the Nacos console, and you can see the services in the service listdemo-providerRegister in the namespacedevUnder. The diagram below:

6.3 Setting up service consumers

Copy the labX-01-SCA-NACos-discovery-Demo02-consumer project from the labX-01-SCA-NACos-Discovery-Demo02-consumer project in section 3.2 setting up service Consumers. Then modify on it, convenient to build ~

6.3.1 Configuration Files

Note: this is basically the same as in “6.2.1 Configuration files”. Repeat.

Modify the application.yaml configuration file to remove the Nacos Discovery configuration item and add it to the configuration file of different environments later. The configuration is as follows:

spring:
  application:
    name: demo-consumer # Spring application name

server:
  port: 28080 # Server port. The default value is 8080
Copy the code

Create the application-dev.yaml configuration file for the development environment, and add the Nacos Discovery configuration item with Namespace dev as the Namespace. The configuration is as follows:

spring:
  cloud:
    nacos:
      Nacos as the configuration item of the registry corresponds to the NacosDiscoveryProperties configuration class
      discovery:
        server-addr: 127.0. 01.: 8848 # Nacos server address
        namespace: 14226a0d-799f-424d-8905-162f6a8bf409 # Nacos specifies the number of namespace dev
Copy the code

Create the application-uat.yaml configuration file for the test environment, and add the Nacos Discovery configuration item with Namespace as UAT. The configuration is as follows:

spring:
  cloud:
    nacos:
      Nacos as the configuration item of the registry corresponds to the NacosDiscoveryProperties configuration class
      discovery:
        server-addr: 127.0. 01.: 8848 # Nacos server address
        namespace: bc8c8c2d-bd85-42bb-ada3-1a8f940ceb20 # Nacos specifies the number of the uAT namespace
Copy the code

6.2.3 Simple test

Next, we use the command line argument for the –spring.profiles. Active configuration item to implement different environments and read different configuration files.

1) first configuration--spring.profiles.activedev, set DemoConsumerApplication to readapplication-dev.yamlConfiguration file. As shown below:

Then start the service consumer with DemoConsumerApplication.

Visit http://127.0.0.1:28080/hello? service consumers Name = yudaoyuanma interface, return the result for “consumer: the provider: yudaoyuanma”. Call the remote service provider [success].

(2) relocation--spring.profiles.activeuat, set DemoConsumerApplication to readapplication-uat.yamlConfiguration file. As shown below:

Then start the service consumer with DemoConsumerApplication.

Visit http://127.0.0.1:28080/hello? service consumers Name = Yudaoyuanma interface, which returns an error message “cannot obtain instance”. Call remote service provider failed.

The demo-provider service has been started, and its Namespace registered with Nacos is dev. Therefore, the demo-consumer service can be invoked. Demo-consumer, the service started in step 2, cannot be invoked.

That is, we can isolate services in different environments through Nacos’s Namespace. In the future, after the open source version of Nacos has complete permissions, each Namespace will provide different AccessKey and SecretKey to ensure that only those who know the account password can connect to the corresponding Namespace, further improving security.

7. Monitor endpoints

The sample code corresponds to the repository:

  • Service provider: LabX-01-SCA-NACos-discovery-Demo01-provider
  • Service consumer: LabX-01-SCA-NACOS-discovery-DEMO03-consumer

Nacos Discovery is based on Spring Boot Actuator. It provides customized monitoring endpoints nacOS-Discovery and obtains Nacos Discovery configuration items and subscribed service information.

At the same time, Nacos Discovery expand the Spring Boot physical built-in health endpoint, through the custom NacosDiscoveryHealthIndicator, access and Nacos server connection status.

Friendly tip: For those who do not know Spring Boot Actuator, you can read the following article “Introduction to Spring Boot Monitoring Endpoint Actuator”.

Let’s build an example of a Nacos Discovery monitoring endpoint. The steps are as follows:

  • First, set up a service providerdemo-providerRegister the service into Nacos.
  • Then, build a service consumerdemo-consumer, invoking the service providerdemo-providerHTTP interface provided. At the same time, configure Nacos Discovery monitoring endpoints for service consumers to be enabled.
  • Finally, access the Nacos Discovery monitoring endpoint of the service consumer to see the monitoring data returned.

7.1 Setting up service Providers

Directly reuse the labX-01-SCA-NACos-discovery-Demo01-Provider project in section 3.1 setting up a Service Provider.

Because the LabX-01-SCA-NACos-discovery-Demo01-Provider project does not subscribe to any services from nacOS, it is not possible to see the full effect of the nacOS-Discovery endpoint. So we will not configure the Nacos Discovery monitoring endpoint for the project for now.

However, in the actual project, it is still possible to enable the Nacos Discovery monitoring endpoint under configuration, at least you can see the Nacos Discovery configuration item.

7.2 Setting up service consumers

Copy the labX-01-SCA-NACos-discovery-Demo03-consumer project from the labX-01-SCA-NACos-Discovery-Demo03-consumer project in section 3.2 setting up service Consumers. Then modify on it, convenient to build ~

7.2.1 Importing Dependencies

In pom. XML file, Spring Boot Actuator dependencies are added. The code is as follows:

<! -- Realizing automatic configuration of the Actuator -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code

7.2.2 Configuration Files

Modify the application.yaml configuration file, and add Spring Boot Actuator configuration items. The configuration is as follows:

management:
  endpoints:
    web:
      exposure:
        include: The '*' Need open endpoints. By default, only the health and INFO endpoints are open. All endpoints can be opened by setting *.
  endpoint:
    The # Health endpoint configuration item corresponds to the HealthProperties configuration class
    health:
      enabled: true # Enable or not. The default value is true.
      show-details: ALWAYS # When to display complete health information. The default is NEVER. Optional WHEN_AUTHORIZED when authorized users; Optional ALWAYS ALWAYS show.
Copy the code

For the role of each configuration item, fat friends look down at the notes added by Nai. If you still don’t understand, read the following article: Introduction to Spring Boot Monitoring Endpoint Actuator.

7.3 Simple Test

① Start the service provider with DemoProviderApplication and start the service consumer with DemoConsumerApplication.

After that, visit http://127.0.0.1:28080/hello? service consumers Name = yudaoyuanma interface, return the result for “consumer: the provider: yudaoyuanma”. A: The remote service provider was successfully invoked.

② Access to service consumersnacos-discoveryMonitoring the endpointhttp://127.0.0.1:28080/actuator/nacos-discovery, the returned result is as follows:

In theory, the “subscribe” field should return information about the subscribed service demo-provider, but it returns nothing. Later, I looked at the source code. I need to register EventListener with Nacos EventDispatcher. Ahem, ahem, this setting feels a bit magical

③ Access to service consumershealthMonitoring the endpointhttp://127.0.0.1:28080/actuator/health, the returned result is as follows:

666. The eggs

So far, we have completed the learning of Spring Cloud Alibaba Nacos Discovery. Here is the official documentation for Nacos:

  • Nacos Official Documentation
  • Spring Cloud Alibaba Official Documentation — Nacos Discovery
  • Official Example of Spring Cloud Alibaba — Nacos Discovery

In addition, those who want to use Nacos as a registry in Spring Boot projects can read the article “Getting Started with Spring Boot Registry”.