07 service registry Nacos application practice

Introduction to Nacos registry

Background analysis

In microservices, the first problem we need to face is how to find services (software is a service), and the second is how to communicate between different services? How to manage each service in the application better and more conveniently, and how to establish the link between various services, so that the registration center was born (for example, Taobao sellers provide services and buyers invoke services).
Zookeeper (Yahoo, APACHE), Eureka (Netfix), Nacos (Alibaba) and Consul (Google) are commonly used registration centers in the market. What are their characteristics and how do we select them? We mainly consider community activity, stability, function and performance For this microservice study, we chose Nacos, which well supports Alibaba's double 11 activities. It can not only be used as a registration center, but also as a configuration center. It has good stability and performance

Nacos overview

Nacos (dynamic naming and configuration service) is a platform for service registration, discovery and configuration management. It was incubated in Alibaba and grew up in the peak test of double 11 in the past decade. It has precipitated its core competitiveness of simplicity, ease of use, stability and reliability and excellent performance. Its official website address is as follows:

https://nacos.io/zh-cn/docs/quick-start.html

Building Nacos services

Download and install

Step 1: to download Nacos, you can directly enter the following address in the browser:

https://github.com/alibaba/nacos/releases

Step 2: select the corresponding version and download it directly, as shown in the figure:

Step 3: decompress Nacos (preferably not to the Chinese directory), and its directory structure is as follows:

Initialize configuration

Step 1:

Find / conf / Nacos mysql The SQL script in the SQL file, then log in to MySQL, create a database based on the description in the script file (name nacos_config, encoding utf8mb4), and execute the script file (or directly use the Nacos mysql.sql sent by the teacher in class). If the script is executed successfully, some tables will be created, as shown in the figure:

Note: when executing this file, the version of mysql must be greater than 5.7 (MariaDB is better than 10.5.11), otherwise the following error will occur:

Step 2:

Open / conf / application Open the default configuration in properties, configure the database to be connected based on your current environment, and the user name and password to be used when connecting to the database (if there is "#" in front, remove it):

### If use MySQL as datasource:
spring.datasource.platform=mysql

### Count of DB:
db.num=1

### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=root

Service startup and access

Step 1: start the Nacos service.

Linux/Unix/Mac startup command (standalone stands for stand-alone mode, non cluster mode):

./startup.sh -m standalone

Windows startup command (standalone stands for stand-alone mode, non cluster mode):

startup.cmd -m standalone

explain:

  1. When executing the execution command, either configure the environment variable or execute it directly in the nacos/bin directory
  2. When nacos starts, Java needs to be configured in the local environment variable_ Home (corresponding to the jdk installation directory),

Step 2: access the Nacos service.

Open the browser and enter http://localhost:8848/nacos Address, the following landing page appears:

The default account password is nacos/nacos

Introduction to service registration and invocation (key points)

Business description

Create two project modules: service provider and service consumer. Both of them should be registered in the NacosServer (the server is essentially a web service, and the port is 8848 by default). Then the service provider can provide remote calling services for service consumers (for example, payment service is the service provider and order service is the service consumer), as shown in the figure:

Create Maven parent project

Create maven module project 01 SCA, which is the parent project of our subsequent project modules. The function of this project is to manage the common dependencies required in the sub modules, as shown in the figure:

Manage its core dependencies through this project, and its pom file contents are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<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>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cy</groupId>
    <artifactId>01-sca </artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring.cloud-version>Hoxton.SR8</spring.cloud-version>
        <spring.cloud.alibaba-version>2.2.5.RELEASE</spring.cloud.alibaba-version>
   </properties>

    <dependencyManagement>
        <dependencies>
            <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>

</project>

For the version, please refer to the following website (it involves a compatibility problem, and its version cannot be specified arbitrarily):

https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E

Note: after the parent project resource initialization is completed, delete the src directory because the parent project is only responsible for dependency management

Producer services creation and registration

Step 1: create a service provider inheritance parent project (01 MSA), and the module name is SCA Nacos provider (when creating a module project, right-click the parent project to create a module).


Step 2: add project dependencies. The key codes are as follows:

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

Step 3: create and modify the configuration file application YML (or application.properties) to realize service registration. The key codes are as follows:

server:
   port: 8081
spring:
  application:
    name: sca-provider
  cloud:
    nacos:
      server-addr: localhost:8848

Note: do not use underscores ("") for service names, A bar ("-") should be used, which is the rule.
Step 4: create a startup class and define the control layer objects and methods for processing requests. The key codes are as follows:

package com.cy;

@SpringBootApplication
public class ScaProviderApplication {

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

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

    @RestController
    public class ProviderController {
        @GetMapping(value = "/provider/echo/{msg}")
        public String doEcho(@PathVariable String msg) {
            return server+"say:Hello Nacos Discovery " + msg;
        }
    }

}

Step 5: start the startup class, and then brush the nacos service to check whether the service registration is successful, as shown in the figure:

Step 6: open the browser and enter http://localhost:8081/provider/echo/msa , and then visit.

Consumer service discovery and invocation

Step 1: create a service consumer inheritance parent project, and the module name is SCA Nacos consumer.

Step 2: add project dependencies. The key codes are as follows:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
  		<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    	</dependency>
</dependencies>

Step 3: modify the configuration file application YML, the key codes are as follows:

server:
  port: 8090
spring:
  application:
    name: sca-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Where to find the service

Step 4: create a startup class and realize service consumption. The key codes are as follows:

package com.cy;
@SpringBootApplication
public class ScaConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScaConsumerApplication.class,args);
    }
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @RestController
    public class ConsumerController{

        @Value("${spring.application.name}")
        private String appName;
        @Autowired
        private RestTemplate restTemplate;
        @GetMapping("/consumer/doRestEcho1")
        public String doRestEcho01(){
            String url = "http://localhost:8081/provider/echo/"+appName;
            System.out.println("request url:"+url);
           return restTemplate.getForObject(url, String.class);
        }
    }
}

Step 5: start the consumer service and enter in the browser http://localhost:8090/consumer/doRestEcho1 Address. If the access is successful, it will appear, as shown in the figure:

Section interview analysis

  • Why register the service with nacos? (to better find these services)
  • In Nacos, how does a service provider renew its contract with the Nacos registry? (5 second heartbeat)
  • For the Nacos service, how does it determine the status of the service instance? (heartbeat detection package, 15,30)
  • How to find the service startup registration configuration class when starting a service? (NacosNamingService)
  • How does the service consumer invoke the services of the service provider? (RestTemplate)

Design and implementation of service load balancing (key)

Introductory case

A service instance can process requests is limited. If the concurrent access of a service instance is relatively large, we will start multiple service instances and let these service instances process concurrent requests with certain policy balancing (polling, weight, random, hash, etc.). How is the service load balancing (Nacos client load balancing) applied in Nacos?

Step 1: modify the ConsumerController class and inject the LoadBalancerClient object,
And add the dorestloadbalancerclientrecho method, and then access the service

  @Autowired
  private LoadBalancerClient loadBalancerClient;
   
  @GetMapping("/consumer/doRestEcho02")
 public String doRestEcho02(){
     ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
     String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
     System.out.println("request url:"+url);
     return restTemplate.getForObject(url, String.class);
     }
 }

Step 2: open the Idea service startup configuration, as shown in the figure:

Step 3: modify the concurrent Run option (if this option is not found, we need to find the corresponding solution through the search engine based on combined query, such as searching idea allow parallel run), as shown in the figure:

Step 4: modify the configuration file port of SCA provider and start it in the mode of 80818082 port respectively.

server:
  port: 8081
spring:
  application:
    name: sca-provider
  cloud:
    nacos:
      server-addr: localhost:8848

After successful startup, access the service list of nacos and check whether the service is successfully registered, as shown in the figure:


Step 4: start the SCA consumer project module, open the browser, and enter the following website for repeated service access:

http://localhost:8090/consumer/doRestEcho02

Then you will find that both services of SCA provider can handle SCA consumer requests.


Here, multiple instances provide services concurrently by load balancing. The default implementation of load balancing here is because Nacos integrates the ribbon. The ribbon and RestTemplate can easily access services. Ribbon is one of the core components of Spring Cloud. The most important function it provides is the load balancing of the client (the client can adopt certain algorithms, such as polling access and accessing the instance information of the server). This function allows us to easily automatically convert the service-oriented REST template requests into service calls in the client load balancing mode.

@LoadBalanced

Added by itshim on Sun, 26 Dec 2021 17:22:04 +0200