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

nacos
├── 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'

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

2. Configuration of nacos

. env file configuration variable (record nacos version information)

NACOS_VERSION=v2.0.4

/env/mysql.env file configuration

MYSQL_ROOT_PASSWORD=root
MYSQL_DATABASE=nacos_devtest
MYSQL_USER=nacos
MYSQL_PASSWORD=nacos

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

SPRING_DATASOURCE_PLATFORM=mysql
MYSQL_SERVICE_HOST=mysql
MYSQL_SERVICE_DB_NAME=nacos_devtest
MYSQL_SERVICE_PORT=3306
MYSQL_SERVICE_USER=nacos
MYSQL_SERVICE_PASSWORD=nacos
MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false

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: org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata

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 com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
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
 */
@RestController
@RequestMapping("home")
public class HomeController {

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

    @NacosValue(value = "${const.name:1}")
    private String name;

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

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

    @RequestMapping("index")
    public String index(){
        return "index";
    }

    @RequestMapping("get")
    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