What are Nacos

Nacos (http://nacos.io) is an easy-to-use platform designed for dynamic service discovery, configuration, and service management. It helps you easily build cloud native applications and microservice platforms.

Install and start Nacos

Download: github.com/alibaba/nac… Version of this article: 1.0.1

Once the download is complete, unzip it.

CD To the nacos/bin directory

According to different platforms, run different commands to start the Nacos service:

Startup command (standalone stands for standalone mode, not cluster mode):

  • Linux/Unix/Mac:sh startup.sh -m standalone
  • Windows:cmd startup.cmd -m standaloneOr double-click thestartup.cmdRun the file.

No accident Your success will start Startup is complete, visit: http://localhost:8848/nacos/, can enter the Nacos service management page, specific as follows:

Default username/password: nacOS/nacOS Login The NACOS registry has been set up

Create service emulation microservices

Project structure Drawing:

  • Spring the Boot: 2.1.6. RELEASE

  • Spring Cloud: Greenwich.SR1

  • Spring Cloud Alibaba: 0.2.2. RELEASE

The tutorial is multi-modular, starting with creating a Maven project as a parent project and introducing common dependencies

Complete pom. XML

<? 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"> < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Xd < / groupId > < artifactId > SpringCloudAlibabaLearn < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < the parent > < groupId > org. Springframework. Boot < / groupId > <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> </parent> <modules>  <module>alibaba-nacos-provider-server</module> <module>alibaba-nacos-consumer-server</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.SR1</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> The < artifactId > spring - the cloud - alibaba - dependencies < / artifactId > < version > 0.2.2. RELEASE < / version > <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
Copy the code

The above content mainly consists of three parts:

  • parent: Defines the Spring Boot version
  • dependencyManagement: The version of Spring Cloud and the version of Spring Cloud Alibaba. Since Spring Cloud Alibaba is not included in the main version management of Spring Cloud, you need to add it yourself
  • dependencies: Dependencies to be used by the current application. Here, the service registration and discovery module of Nacos is mainly newly added:

Spring – the cloud – starter – alibaba – nacos – discovery. Since versions have already been introduced in dependencyManagement, there is no need to specify a version here. Then there is the spring-boot startup dependency

Now create two applications (service provider and service consumer) on the parent module to verify the registration and discovery of the service

Creating a service provider

1. Create a SpringBoot project

Then name the project, organization, etc

2. Edit the pom. XML file
<? 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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.xd</groupId> <artifactId>SpringCloudAlibabaLearn</artifactId> < version > 1.0 - the SNAPSHOT < / version > < relativePath >). / < / relativePath > < / parent > < artifactId > alibaba - nacos - the provider - server < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > <name> Alibaba-nacos-provider-server </name> <description> Service provider </description> <properties> <java.version>1.8</java.version> </properties> <dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code
3.application.properties

Configure the service name and nacOS registry address

# Custom port number
server.port=8080
# Service provider
spring.application.name=provider-service
Register in the NACOS registrySpring. Cloud. Nacos. Discovery. Server - addr = 127.0.0.1:8848Copy the code
4. Create the request class and implement an interface
package com.xd.alibabanacosproviderserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * @restController indicates the controller layer. * @enableDiscoveryClient Enables the service discovery function. */ @restController@enableDiscoveryClient @SpringBootApplication public class AlibabaNacosProviderServerApplication { public static void main(String[] args) { SpringApplication.run(AlibabaNacosProviderServerApplication.class, args); } @GetMapping("/echo/{name}")
   public String echo(@PathVariable String name) {
      return "hello "+ name; }}Copy the code

Mainly expressed as:

@springBootApplication defines a SpringBoot application;

@enableDiscoveryClient Enables service registration and discovery in Spring Cloud. Since the spring-Cloud-starter-Alibaba-nacos-Discovery module is introduced here, So those service governance-related interfaces defined in Spring Cloud Common will use Nacos’s implementation

5. Start the program

After the startup program is complete, you will find the instructions printed by the console that you have registered with NACOS

6. Check the NACOS registry to see if you are registered

Switch to the service list: This displays all services currently registered, as well as the number of clusters, instances, and healthy instances for each service.

Click details, we can also see the specific instance information of each service, as shown below:

The service provider has been created so far

Creating service consumers

1. Create a Spring Boot project

Same procedure, no more explanation here

2. Edit the pom. XML file
<? 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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.xd</groupId> <artifactId>SpringCloudAlibabaLearn</artifactId> < version > 1.0 - the SNAPSHOT < / version > < relativePath >). / < / relativePath > < / parent > < artifactId > alibaba - nacos - the provider - server < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > <name> Alibaba-nacos-provider-server </name> <description> Service consumer </description> <properties> <java.version>1.8</java.version> </properties> <dependencies> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code
3.application.properties

Configure the service name and nacOS registry address

server.port=8081
# Serve consumers
spring.application.name=consumer-service
Register service to NACOSSpring. Cloud. Nacos. Discovery. Server - addr = 127.0.0.1:8848Copy the code
4. Create the application main class and implement an interface that invokes the service provider’s interface.
package com.xd.alibabanacosconsumerserver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * @restController indicates the controller layer. * @enableDiscoveryClient Enables the service discovery function. */ @restController@enableDiscoveryClient @SpringBootApplication public class AlibabaNacosConsumerServerApplication { public static void main(String[] args) { SpringApplication.run(AlibabaNacosConsumerServerApplication.class, args); } @Autowired LoadBalancerClient loadBalancerClient; @GetMapping("/echo/{name}")
    public String test(@PathVariable("name") String name) {// Use the load balancing interface in Spring Cloud Common to select the service provider node to implement the interface. Call // serviceId to Spring.application. name ServiceInstance serviceInstance = loadBalancerClient.choose("provider-service");
        String url = serviceInstance.getUri() + "/echo/" + name;
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        return "from: " + url + ",return: "+ result; }}Copy the code

The LoadBalancerClient interface in Spring Cloud Common is used to pick up service instance information. It then gets the accessible URI from the selected instance information and concatenates the interface rules of the service provider to initiate the call.

5. Start the service consumer program

Also open the NACOS registry is not registered successfully

Already seem to register, and then open the browser visit: http://localhost:8081/echo/lhd

This paper simulates the process of calling each other between services in microservices. However, it is obvious that the implementation of such a process is still cumbersome. Several ways of service consumption will be explained later

Iv. Reference Materials:

  • Nacos official documentation: nacos. IO /zh-cn/
  • Nacos blog: blog.didispace.com/spring-clou…

Five. Code examples

  • Making: github.com/LiHaodong88…
  • A code cloud: gitee.com/li_haodong/…

If you are interested in these, welcome to star, follow, favorites, forward to give support!