[Reproduced please indicate the source] :Juejin. Cn/post / 684490…

1. Nacos is introduced

1.1 Key features of Nacos

Nacos is dedicated to discovering, configuring, and managing microservices. Nacos supports the discovery, configuration, and management of almost all major types of “services” :

  • Kubernetes Service
  • gRPC&Dubbo RPC Service
  • Spring Cloud RESTful Service

Key features of Nacos include:

  • Service discovery and Service Health Monitoring Nacos supports DNs-based 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.

    Nacos provides real-time health checks on services to prevent requests from being sent to unhealthy hosts or service instances. Nacos supports health checks at the transport layer (PING or TCP) and the application layer (e.g. HTTP, MySQL, user-defined). Nacos provides two health check modes: Agent report mode and server active check mode for complex cloud environments and network topologies, such as VPCS and edge networks. Nacos also provides a unified health check dashboard to help you manage service availability and traffic based on health status.

  • 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 configuration eliminates the need to redeploy applications and services when configuration changes, making configuration management more efficient and agile.

    Centralized configuration management makes it easier to implement stateless services and make it easier for services to scale flexibly on demand.

    Nacos provides an easy-to-use UI (sample console Demo) to help you manage the configuration of all your services and applications. Nacos also provides a number of out-of-the-box configuration management features including configuration version tracking, Canary publishing, one-click rollback configuration, and client configuration update status tracking to help you more securely manage configuration changes and reduce the risks associated with configuration changes in a production environment.

  • Dynamic DNS Service The dynamic DNS service supports weighted routing, enabling you to implement load balancing at the middle layer, flexible routing policies, traffic control, and simple DNS resolution services on the data center Intranet. Dynamic DNS services also make it easier for you to implement DNS protocol-based service discovery to help eliminate the risk of coupling to vendor-proprietary service discovery apis.

    Nacos provides some simple DNS APIs TODO to help you manage your service’s associated domain name and available IP:PORT list.

  • Service and Metadata Management Nacos allows you to manage all services and metadata in your data center from a microservices platform construction perspective. This includes management service description, life cycle, static dependency analysis of the service, health of the service, traffic management of the service, routing and security policies, SLA of the service, and most importantly metrics statistics.

1.2 ECOLOGICAL map of Nacos

Nacos seamlessly supports some mainstream open source ecosystems, for example

  • Spring Cloud
  • Apache Dubbo and Dubbo Mesh TODO
  • Kubernetes and CNCF TODO.

Using Nacos simplifies service discovery, configuration management, service governance, and management solutions, making it easier to discover, manage, share, and compose microservices.

2. Start the Nacos service

2.1 Preparing the environment

Nacos relies on the Java environment to run. If you build and run Nacos from code and need to configure the Maven environment for this, make sure you install it in one of the following versions:

  • The 64-bit OS supports Linux, Unix, Mac, and Windows. Linux, Unix, and Mac are recommended.
  • 64-bit JDK 1.8+; Download & Configure.
  • Maven 3.2 x +; Download & Configure.

2.2 Download the source code or install the package

You can get Nacos both from source code and distribution packages.

  • Download the source code from Github
  git clone https://github.com/alibaba/nacos.git
  cd nacos/
  mvn -Prelease-nacos clean install -U  
  ls -al distribution/target/
  cd distribution/target/nacos-server-$version/nacos/bin
Copy the code
  • Download the compressed package after compilationYou can fromLatest Stable releasedownloadnacos-server-$version.zipThe package.
    unzip nacos-server-$versionZip or tar -xvf nacos-server-$version.tar.gz
    cd nacos/bin
Copy the code

2.3 Starting the Server

  • Linux/Unix/Mac startup command (standalone stands for standalone mode, not cluster mode): sh startup. Sh -m standalone

  • Run the CMD startup. CMD command or double-click the startup.

2.4 Shutting down the Server

  • Linux/Unix/Mac sh shutdown.sh

  • Windows CMD shutdown. CMD or double-click the shutdown. CMD file to run.

2.5 the console

The browser open http://127.0.0.1:8848/nacos default user name password is nacos

3. Enable service discovery

3.1 the service provider

Add dependencies:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> < artifactId > spring - the cloud - starter - alibaba - nacos - discovery < / artifactId > < version >. 0.9.0 RELEASE < / version > < / dependency >Copy the code

The configuration file

Server: port: 8021 Spring: Application: name: service-provider Cloud: nacos: Discovery: server-addr: 127.0.0.1:8848Copy the code

Start the class

@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderApplication {

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

	@RestController
	class EchoController {
		@GetMapping(value = "/echo")
		public String echo(String name) {
			return "Hello "+ name; }}}Copy the code

The startup service is visible in the list of services on the Nacos console.

3.2 service – consumer

Add dependencies:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> < artifactId > spring - the cloud - starter - alibaba - nacos - discovery < / artifactId > < version >. 0.9.0 RELEASE < / version > < / dependency > <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Copy the code

The configuration file

Server: port: 8011 Spring: Application: name: service-consumer Cloud: nacos: Discovery: server-addr: 127.0.0.1:8848Copy the code

Here the Provider client is invoked using feign

@FeignClient(name = "service-provider")
public interface NacosClient { 
    @GetMapping(value = "/echo")
    ResponseEntity<String> echo(String name) ;
}
Copy the code

Start the class

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApplication {

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

    @RestController
    public class TestController {
         @Autowired
          private NacosClient client;

          @GetMapping(value = "/echo")
          public ResponseEntity<String> echo(String name) {
			returnclient.echo(name); }}}Copy the code

Start the Consumer, and then go to http://localhost:8011/echo? Name =zhangsan You can see the response of the provider.

4. Start configuration management

Change the Service-Consumer project to take configuration dependencies from Nacos

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> < artifactId > spring - the cloud - starter - alibaba - nacos - discovery < / artifactId > < version >. 0.9.0 RELEASE < / version > < / dependency > <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> < artifactId > spring - the cloud - starter - alibaba - nacos - config < / artifactId > < version >. 0.9.0 RELEASE < / version > < / dependency >Copy the code

The configuration file

spring:
  application:
    name: service-consumer
  profiles:
    active: single
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        prefix: ${spring.application.name}
        file-extension: yaml
Copy the code

For testing purposes, add a configuration variable to TestController

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApplication {

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

    @RestController
    @RefreshScope
    public class TestController {
          @Autowired
          private NacosClient client;
          @Value("${useLocalCache:false}")
          private boolean useLocalCache;

          @GetMapping("/get")
          public boolean get() {
            return useLocalCache;
          }

          @GetMapping(value = "/echo")
          public ResponseEntity<String> echo(String name) {
			returnclient.echo(name); }}}Copy the code

In Nacos Spring Cloud, the full format of dataId is as follows:

${prefix}-${spring.profile.active}.${file-extension}
Copy the code
  • prefixThe default isspring.application.nameIs also available through the configuration itemspring.cloud.nacos.config.prefixTo configure.
  • spring.profile.activeIs the profile corresponding to the current environmentNote: whenspring.profile.activeIf null, the corresponding concatenate-Also will not exist, the dataId splicing format becomes${prefix}.${file-extension}
  • file-exetensionFor the data format of the configuration content, you can pass the configuration itemspring.cloud.nacos.config.file-extensionTo configure. Currently only supportedpropertiesandyamlType.

Open configuration Management on the Nacos console and add configuration items

  • Data ID:service-consumer-single.yaml
  • Configuration contents:
Server: port: 8011 Spring: Cloud: nacos: Discovery: server-addr: 127.0.0.1:8848 useLocalCache:false
Copy the code

Restart the service – consumer, visit http://localhost:8011/echo? Name = zhangsan can see the provider response, visit http://localhost:8011/get, return to false content at this time. In Nacos useLocalCache console configuration management update values: true, visit http://localhost:8011/get again, this time return to true content, show the useLocalCache value in program has been updated dynamically.

[Reproduced please indicate the source] :Juejin. Cn/post / 684490…