Using nacos as the configuration center

nacos Alibaba is an open source application architecture. Its core is "service", which provides a series of functions such as service discovery, configuration center and micro service management around services.

The reason for choosing nacos is Chinese ecology, which is simple and easy to use.

Key features of nacos (extracted from official nacos documents)

  • Service discovery and service health monitoring

    Nacos supports DNS based and RPC based service discovery. Service provider usage Native SDK,OpenAPI , or one Independent Agent TODO After registering the Service, Service consumers can use it DNS TODO or HTTP&API Find and discover services.

    Nacos provides real-time health inspection of services to prevent sending requests to unhealthy hosts or service instances. Nacos supports health check of transport layer (PING or TCP) and application layer (such as HTTP, MySQL, user defined). For the health inspection of services in complex cloud environment and network topology environment (such as VPC, edge network, etc.), Nacos provides two health inspection modes: agent reporting mode and server-side active detection mode. Nacos also provides a unified health check dashboard to help you manage service availability and traffic according to health status.

  • Dynamic configuration service

    Dynamic configuration service allows you to manage the application configuration and service configuration of all environments in a centralized, external and dynamic way.

    Dynamic configuration eliminates the need to redeploy applications and services when configuration changes, making configuration management more efficient and agile.

    Configuration centralized management makes it easier to implement stateless services and make it easier for services to expand flexibly on demand.

    Nacos provides a simple and easy-to-use UI( Console sample Demo )Help you manage the configuration of all services and applications. Nacos also provides a series of out of the box configuration management features, including configuration version tracking, Canary release, one click rollback configuration and client configuration update status tracking, to help you more safely manage configuration changes and reduce the risks caused by configuration changes in the production environment.

  • Dynamic DNS Service

    The dynamic DNS service supports weighted routing, which makes it easier for you to realize middle tier load balancing, more flexible routing strategy, traffic control and simple DNS resolution service in the intranet of the data center. Dynamic DNS services also make it easier for you to implement DNS protocol based service discovery to help you eliminate the risk of coupling to the vendor's private service discovery API.

    Nacos provides some simple DNS APIs TODO Help you manage the associated domain name of the service and the list of available IP: ports

  • Service and metadata management

    Nacos enables you to manage all services and metadata in the data center from the perspective of micro service platform construction, including service description, life cycle, static dependency analysis of services, health status of services, traffic management of services, routing and security policies, SLA of services and the most important statistics of metrics.

  • More feature lists

nacos is integrated through springboot as the configuration center

1. nacos installation

There are many ways to install nacos. Here is the docker mode, nacos stand-alone mode + mysql8

Prepare a server or local machine, install the following tree and allocate it reasonably

├── env     					#mysql and nacos configuration (user password, link parameters, etc.)
├── init.d  					#nacos startup initialization allocation parameters (memory size, etc.)
├── mysql						#mysql mount directory
└── standalone-logs				#nacos mount directory

Using docker compose management, the sample yaml file is as follows

version: '3.8'

    image: nacos/nacos-server:${NACOS_VERSION}
    container_name: nacos-standalone-mysql
      - ./nacos/env/nacos-standlone-mysql.env
      - ./nacos/standalone-logs/:/home/nacos/logs
      - ./nacos/init.d/
      - "8848:8848"
      - "9848:9848"
      - "9555:9555"
      - mysql
    restart: always
    container_name: mysql-for-nacos
    image: nacos/nacos-mysql:8.0.16
      - ./nacos/env/mysql.env
      - ./nacos/mysql:/var/lib/mysql
      - "33061:3306"

2. Configuration of nacos

. env file configuration variable (record nacos version information)


/env/mysql.env file configuration


/env/nacos-standlone-mysql.env file configuration


3. Start nacos

Create and start nacos

docker-compose up -d nacos

view log

docker-compose logs -f nacos

The project is started successfully, and the banner of nacos appears, which can be accessed directly through the link printed by the console. If it is not accessed locally, the corresponding public network ip needs to be provided

4. Access nacos and create the corresponding configuration

Access Nacos. If the port is not changed locally, http://localhost:8848/nacos , the default user password is the Nacos specified in the configuration file

Create a new one in the background. Note that the Data ID is unique and cannot be repeated. Group can be used by default

Different configuration formats can be specified here. yaml is recommended, but there are some pitfalls (you should pay attention to the corresponding version when integrating nacos config with springboot)

5. nacos and springboot are integrated. After the springboot seems to be 2.4 or more, if yaml format is used as the configuration, it needs to be specified in the project, otherwise it will be prompted

Caused by: java.lang.ClassNotFoundException:

Because of this, the higher version of configurationbeanfactorymatadata was removed.

There are two solutions: 1. Modify the source code and replace the ConfigurationBeanFactoryMetadata; 2. Use @ NacosPropertySource(dataId = "springboot demo", autorefressed = true, type = configtype. Yaml) to specify yaml and upgrade the dependency. ps: upgrade dependency has another advantage, if Nacos. Com is used here If the version is changed to 0.2.1, it will be found that the multiple layers in yaml configuration cannot get the value, and only the last layer can get the value, but this is of no use.

The configured yaml example is as follows. Note that the data ID needs to be consistent with that in our project

6. Test, open an http interface, dynamically modify the configured value in the background of nacos, and the system will refresh automatically. Note @ NacosValue(value = "${const.age:2}", autorefreased = true)

autoRefreshd needs to be guaranteed to be true.

package com.example.demo1.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

 * Created by ypc
 * 2022/3/2 16:00
 * Description: TODO
public class HomeController {

    @NacosValue(value = "${const.age:2}", autoRefreshed = true)
    private Integer age;

    @NacosValue(value = "${}")
    private String name;

    @Value(value = "${server.port:1}")
    private String port;

    @NacosValue(value = "${var.age:22222}", autoRefreshed = true)
    private Integer age1;

    public String index(){
        return "index";

    public JSONObject get(){
        JSONObject object = new JSONObject();
        object.put("age", age);
        object.put("age1", age1);
        object.put("port", port);
        object.put("name", name);
        return object;


Keywords: Java Docker Spring Boot intellij-idea

Added by mrinfin1ty on Wed, 02 Mar 2022 10:52:44 +0200