Spring Cloud Alibaba:Nacos Used as Registry and Configuration Center

Posted by nicephotog on Sat, 07 Dec 2019 10:57:33 +0100

SpringBoot e-commerce project mall (20k+star) address: https://github.com/macrozheng/mall

abstract

Spring Cloud Alibaba is dedicated to providing one-stop solutions for microservice development. As one of its core components, Nacos can be used as a registry and configuration center. The usage of Nacos is described in detail in this article.

Introduction to Nacos

Nacos is dedicated to helping you discover, configure, and manage microservices.Nacos provides an easy-to-use set of features to help you quickly implement dynamic service discovery, service configuration, service metadata, and traffic management.

Nacos has the following features:

  • Service discovery and service health monitoring: supports DNS-based and RPC-based service discovery, supports real-time health checks of services, and prevents requests from unhealthy hosts or service instances;
  • Dynamic configuration services: Dynamic configuration services allow you to manage application and service configurations for all environments in a centralized, externalized, and dynamic manner.
  • Dynamic DNS services: Dynamic DNS services support weighted routing, which makes it easier for you to achieve middle-tier load balancing, more flexible routing strategies, traffic control, and simple DNS resolution services within the data center intranet;
  • Services and their metadata management: Supports the management of all services and metadata in a data center from the perspective of the construction of a micro-service platform.

Use Nacos as the registry

Install and run Nacos

  • First we download Nacos from the official website. Here we download the nacos-server-1.1.4.zip file at: https://github.com/alibaba/na...
  • Configuring the JAVA_HOME environment variable will result in Nacos not running if it is not configured;
JAVA_HOME=D:\developer\env\Java\jdk1.8.0_91
  • Unzip the installation package and run startup.cmd directly from the bin directory.
  • After successful operation, visit http://localhost:8848/nacos to view Nacos's home page. The default account passwords are nacos.

Create an application to register with Nacos

We demonstrate the capabilities of service registration and discovery by adapting consul-user-service and consul-ribbon-service, mainly by changing the original Consul registry support to Nacos registry support.

  • Create nacos-user-service module and nacos-ribbon-service module;
  • If you want to use components of Spring Cloud Alibaba, you need to add the following configuration in pom.xml;
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
  • Modify the dependencies to change the dependencies found in the original Consul registration to those of Nacos:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  • Modify the configuration file application.yml to change the registration discovery configuration of Consul to Nacos:
server:
  port: 8206
spring:
  application:
    name: nacos-user-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Configure Nacos address
management:
  endpoints:
    web:
      exposure:
        include: '*'
  • Run two nacos-user-service s and one nacos-ribbon-service, and you can see the following information on the Nacos page:

Load Balancing Function

Since we run two nacos-user-service s and the nacos-ribbon-service calls its interface by default, we call the nacos-ribbon-service interface to demonstrate the load balancing functionality under this scenario.

Multiple calls to the interface: http://localhost : 8308/user/1, you can see that two consoles of nacos-user-service alternately print the following information.

2019-11-06 14:28:06.458 INFO 12092 --- [nio-8207-exec-2] c.macro.cloud.controller.UserController: Get user information based on id, user name is macro:

Use Nacos as the configuration center

We demonstrate the capabilities of configuration management by creating a nacos-config-client module and adding configuration information to the Nacos page.

Create nacos-config-client module

  • Add dependencies to pom.xml:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  • Add the configuration file application.yml, enabling the configuration of the dev environment:
spring:
  profiles:
    active: dev
  • Add the configuration file bootstrap.yml to configure Nacos as the configuration center:
server:
  port: 9101
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos address
      config:
        server-addr: localhost:8848 #Nacos address
        file-extension: yaml #Here we get the configuration of the yaml format
  • Create a ConfigClientController to get configuration information from the Nacos Configuration Center:
/**
 * Created by macro on 2019/9/11.
 */
@RestController
@RefreshScope
public class ConfigClientController {

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/configInfo")
    public String getConfigInfo() {
        return configInfo;
    }
}

Add Configuration to Nacos

  • Let's start with the format of the dataid in Nacos and its relationship to the properties in the SpringBoot configuration file:
${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
  • For example, now we want to get the yaml configuration of an application named nacos-config-client in a dev environment with the following dataid:
nacos-config-client-dev.yaml
  • Add the following configuration according to the above dataid:
config:
  info: "config info for dev"
  • Fill in the configuration diagram:

  • Start nacos-config-client and call the interface to view the configuration information: http://localhost:9101/configInfo
config info for dev

Dynamic refresh configuration for Nacos

As long as we modify the configuration information in Nacos and call the interface to view the configuration again, we will find that the configuration has been refreshed, and that both Nacos and Consul support dynamic refresh of the configuration.When we modify the configuration on the Nacos page and publish it, the application refreshes the configuration and prints the following information

2019-11-06 14:50:49.460  INFO 12372 --- [-localhost_8848] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ec395f8e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-06 14:50:49.608  INFO 12372 --- [-localhost_8848] c.a.c.n.c.NacosPropertySourceBuilder     : Loading nacos data, dataId: 'nacos-config-client-dev.yaml', group: 'DEFAULT_GROUP'
2019-11-06 14:50:49.609  INFO 12372 --- [-localhost_8848] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='nacos-config-client-dev.yaml'}, NacosPropertySource {name='nacos-config-client.yaml'}]}
2019-11-06 14:50:49.610  INFO 12372 --- [-localhost_8848] o.s.boot.SpringApplication               : The following profiles are active: dev
2019-11-06 14:50:49.620  INFO 12372 --- [-localhost_8848] o.s.boot.SpringApplication               : Started application in 0.328 seconds (JVM running for 172.085)
2019-11-06 14:50:49.638  INFO 12372 --- [-localhost_8848] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [config.info]

Reference material

Official documents for Spring Cloud Alibaba: https://github.com/alibaba/sp...

Modules used

springcloud-learning
├── nacos-config-client -- For demonstration nacos As Configuration Center nacos Client
├── nacos-user-service -- Register with nacos Offers User object CRUD Service of interface
└── nacos-ribbon-service -- Register with nacos Of ribbon Service Call Test Service

Project Source Address

https://github.com/macrozheng/springcloud-learning

Public Number

mall project In the full series of learning tutorials, focus on the first time public number is available.

Topics: Java Spring github DNS SpringBoot