SpringBoot集成Nacos做動態配置中心-不重啟服務



title: "SpringBoot集成Nacos僅做動態配置中心-不重啟服務"
categories: Nacos
tags: Nacos
author: LIUREN

SpringBoot集成Nacos做動態配置中心-不重啟服務

Nacos 致力於幫助您發現、配置和管理微服務。Nacos 提供了一組簡單易用的特性集,幫助您快速實現動態服務發現、服務配置、服務元數據及流量管理。他也可以作為動態配置中心來使用。下面我就當它是動態配置中心,做一個demo

協議:CC BY-SA 4.0 https://creativecommons.org/licenses/by-sa/4.0/

版權聲明:本文為原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。

Nacos

如果此文章表述的不清晰可以參考官方的文檔:https://nacos.io/zh-cn/docs/quick-start-spring-boot.html

下載Nacos的服務端版本

下載地址:nacos-server-1.4.1.zip 具體下載地址自行百度。github能下不過有點慢。

本應用主要在Windows 10上測試

然后解壓

到nacos的bin目錄下執行cmd命令行(此為測試,主要是單例啟動)

startup.cmd -m standalone

新建一個Springboot的Maven項目如圖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.hainan.www</groupId>
    <artifactId>SpringBoot-Nacos</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot-Nacos</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        <latest.version>0.2.7</latest.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
		    <groupId>com.alibaba.boot</groupId>
		    <artifactId>nacos-config-spring-boot-starter</artifactId>
		    <version>${latest.version}</version>
		</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.hainan.www.SpringBootNacos.SpringBootNacosApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

SpringBootNacosApplication.java

package com.hainan.www;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;

@SpringBootApplication
@NacosPropertySource(dataId = "haiguan", autoRefreshed = true)
@NacosPropertySource(dataId = "redis", autoRefreshed = true)
public class SpringBootNacosApplication {

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

}

ConfigController.java

package com.hainan.www.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.nacos.api.config.annotation.NacosValue;

@RequestMapping("config")
@RestController
public class ConfigController {

	@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;
	// 該方法是獲取nacos服務端配置的dataCode編碼,如果未配置該字段默認2021010,支持自動刷新
	@NacosValue(value = "${dataCode:2021010}", autoRefreshed = true)
	private String dataCode;
	
	@NacosValue(value = "${redisPort:6673}", autoRefreshed = true)
	private String redisPort;
	
	@NacosValue(value = "${spring.qq.name:6673}", autoRefreshed = true)
	private String springApplicationName;
	
	@NacosValue(value = "${spring.redis.host:6673}", autoRefreshed = true)
	private String springRedisHost;
	
    @GetMapping("/get")
    @ResponseBody
    public boolean get() {
    	System.out.println("useLocalCache==>" + useLocalCache);
    	
    	System.out.println("dataCode=>>>>>>" + dataCode);
    	
    	System.out.println("redisPort=>>>>>>" + redisPort);
    	
    	
    	System.out.println("springApplicationName=>>>>>>" + springApplicationName);
    	
    	System.out.println("springRedisHost=>>>>>>" + springRedisHost);
        return useLocalCache;
    }
}

application.yml


spring:
  application:
    name: SpringBoot-Nacos
nacos:
  config:
    server-addr: 127.0.0.1:8848

首先確定nacos-server已經啟動

然后啟動Springboot項目

配置nacos-server端

登錄地址如下:http://127.0.0.1:8848/ nacos/nacos

如此配置然后調用springboot的get方法

地址:

http://localhost:8080/config/get

看控制台打印信息如下:

useLocalCache==>true
dataCode=>>>>>>20210204
redisPort=>>>>>>6379
springApplicationName=>>>>>>SpringBoot-sss
springRedisHost=>>>>>>127.0.0.1:6379

主要注意的問題是:

nacos如果默認直接啟動,使用的是其自帶的derby數據庫;如果想使用mysql數據庫則需要到nacos-server-1.4.1.zip解壓縮包下的conf下把下列注解解開

如果mysql是8.0版本的話,使用官網文檔會報錯需要在db.url.0=**********&allowPublicKeyRetrieval=true 加上&allowPublicKeyRetrieval=true

#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
spring.datasource.platform=mysql

### Count of DB:
db.num=1

### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
db.user.0=root
db.password.0=root

同時把conf目錄下的nacos-mysql.sql導入到mysql數據庫中

這樣就可以動態修改配置內容了,而且不用重啟服務

Nacos對yaml格式解析不是特別好,注意使用yaml的配置格式容易獲取不到對應的內容

博客地址:https://www.codepeople.cn

=====================================================================

微信公眾號:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM