This article is intended for those with basic Java knowledge

Author: HelloGitHub- Qin Ren

HelloGitHub launched “explain open source project” series, today to bring you an open source Java version can achieve dynamic service discovery, configuration and service management platform — Nacos, it is alibaba team open source in line with all the people’s use habits, and rich Chinese documentation, open source community is particularly active.

Project source code address: github.com/alibaba/nac…

I. Project introduction

Before we choose to use a tool, we should look at the products in the same category to see its value.

Three registries

The name of the Configuration center The registry Rely on Access protocol Version of the iteration Integration support To fit degree
Eureka Does not support support No dependencies on other components HTTP None Version Upgrade SpringCloud integration Easy, English interface, not in line with Chinese custom
Consul support support No dependencies on other components HTTP/DNS Version iteration SpringCloud, K8S Complex, English interface, not in line with Chinese habits
Nacos support support No dependencies on other components Dynamic DNS HTTP / / UDP Version iteration Dubbo, SpringCloud, K8S Easy, Chinese documents and community, in line with the habits of Chinese people

Provides an easy-to-use feature set to help developers quickly implement dynamic service discovery, service configuration, service metadata, and traffic management. Main features:

  • Service discovery: Supports DNS and RPC-based service discovery. After a Service provider registers a Service using a native SDK, OpenAPI, or a separate Agent TODO, Service consumers can use DNS TODO or HTTP&API to find and discover services.
  • Service health monitoring: Provides real-time health checks on services to prevent requests from being sent to unhealthy hosts or service instances.
  • Dynamically configured services: Dynamically configured services allow you to manage application and service configurations for all environments in a centralized, external, and dynamic manner.
  • Dynamic DNS service: The dynamic DNS service supports weighted routing, facilitating load balancing at the middle layer, flexible routing policies, traffic control, and simple DNS resolution services on the data center Intranet.
  • Services and their metadata management: Nacos enables users to manage all services and metadata in the data center from a microservice platform construction perspective, including managing service descriptions, life cycles, static dependency analysis of services, health of services, traffic management of services, routing and security policies, SLA of services, and most importantly metrics statistics.

Nacos ecological figure

Second,SpringBootIn actual combat

The main functions of Nacos are configuration centers and registries.

  • Configuration center: through theNacosTo dynamically obtain the configuration information without restarting the micro service.
  • Registry: Create two microservices: service provider and service consumer for inter-microservice invocation. To invoke the provider’s interface, the consumer simply declares the provider’s microservice name and the interface’s request address,NacosCan accurately find the corresponding interface.

2.1 run Nacos

Download: github.com/alibaba/nac…

unzip nacos-server-$version.zip  # decompression
cd nacos/bin
startup.cmd -m standalone # Single machine mode
Copy the code

Visit the home page

Nacos access address:http://localhost:8848/nacos/Default password: nacos The following figure is displayed on the NACOS page:

2.2 Configuration Center

Create a microservice project

There are three main ways to create a SpringBoot project: through a website, IntelliJ IDEA’s Spring Initializr tool, and Maven to create a project.

The poM file for the project reads as follows:

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

    <! -- Nacos-config Spring Cloud dependency -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>. 0.9.0 RELEASE</version>
    </dependency>
Copy the code

The bootstrap. Yml configuration

spring:
  application:
    name: nacos-config
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848
        file-extension: yaml
        prefix: nacos-config
  profiles:
    active: dev
Copy the code

Nacos configuration

NacosCreate configuration file name format:${prefix}-${spring.profile.active}.${file-extension}, the previous stepbootstrap.ymlI want to create a configuration named:nacos-config-dev.yaml, as follows:

Create a Controller

Take the function of dynamically obtaining user names as an example:

Create an external interface /username as follows:

@RestController
@RefreshScope
public class ConfigController {

    @Value("${username:wangzg}")
    private String username;

    @RequestMapping("/username")
    public String userNameInfo(a) {
        returnusername; }}Copy the code

Note: The @refreshScope annotation is added to the Controller to implement hot loading of the configuration.

The verification results

Run the project locally, and you can see that when the project starts, port has changed to port 8090 that we configured on Nacos.

In the browser to access link: http://localhost:8090/username, return testuser with. To change the value of username on Nacos, there is no need to restart the micro-service, and the value of username will change dynamically when the link is re-requested. It can be seen that Nacos implements hot loading function as the configuration center.

2.3 Registry

  1. Creating a service provider

For details about how to create a microservice, see the preceding configuration. The external interface /sayHello code is as follows:

@RestController
public class ProviderController {

    @GetMapping("/sayHello")
    public String sayHello(@RequestParam(value = "name",defaultValue = "helloWord")String sayHello){

        return "tom say: "+ sayHello; }}Copy the code

Start the service, access to the address: http://localhost:8099/sayHello, can output: Tom say: helloWord, micro – service has been created successfully.

  1. Creating service consumers

The FeignClient approach is used to implement cross-service calls (you can also explore the RestTemplate approach if you are interested).

Pom file

Maven dependencies for Feigin-Client are added to the NACos-consumer POM file.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Copy the code

Add annotations

Add an annotation @enableFeignClients to the microservices startup class * application.java.

Create FeignClient

@FeignClient("nacos-provider")
public interface ProviderClient {

    @GetMapping("/sayHello")
    String sayHello(@RequestParam(value = "name", defaultValue = "wangzg", required = false) String name);
}
Copy the code

Note: The name passed in by the FeignClient annotation specifies the name of FeignClient. If the project uses the Ribbon, the name attribute will be used as the name of the microservice for service discovery.

Create ConsumerController

@RestController
public class ConsumerController {

    @Autowired
    ProviderClient providerClient;

    @GetMapping("/hi-feign")
    public String hiFeign(a){
       return providerClient.sayHello("feign"); }}Copy the code

Restart the project and visit http://localhost:8090/hi-feign in the browser. The correct response is displayed in the browser. Nacos-consumer successfully invokes the nacos-Provider service.

Here’s a sequence diagram of the request flow to make it clear.

Project address: github.com/hellowHuaai…

Three, the last

Microservices have four characteristics:

  • Small (small granularity of microservices)
  • Standalone (independently deployed to run and scale)
  • Light (simple and lightweight system)
  • Loose (high cohesion and low coupling)

To complete a complex system, many microservice units are often needed, and it is very necessary to connect each microservice and complete the unified management of microservice. Therefore, the products of integrated service management center and configuration center come into being, and Nacos is the leader among them!

At this point in the tutorial, you should know something about Nacos as well! The fastest way to learn is to imitate, and then by drawing inferences from one example to another. Each new tool is the innovation of the old tool, interested partners can refer to my case above, in practice will find more fun!

Iv. Reference materials

  • IO/zh-CN /docs/…