springboot整合nacos config
阿新 • • 發佈:2021-06-26
前置知識:nacos已經跑起來;
建立簡單案例如下,首先建立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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jingzhe</groupId> <artifactId>configdemo</artifactId> <version>1.0-SNAPSHOT</version> <!-- 父依賴均是springboot--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> </parent> <dependencies> <!--nacos配置相關;版本會引入springcloud alibaba當中的版本,也就是2.2.5.RELEASE--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <dependencyManagement> <!--其中,scope和type是有必要的,否則maven會報錯哦--> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.2.5.RELEASE</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> </project>
ConfigDemoApplication.java:
package com.jingzhe; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author: Xu Xiang @createTime: 2021/6/26 18:06 * Description: */ @SpringBootApplication public class ConfigDemoApplication { public static void main(String[] args) { SpringApplication.run(ConfigDemoApplication.class); } }
TestController.java:
package com.jingzhe; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author: Xu Xiang @createTime: 2021/6/26 18:08 * Description: * 1.RefreshScope(org.springframework.cloud.context.scope.refresh)是spring cloud提供的一種特殊的scope實現,用來實現配置、例項熱載入; */ @RestController @RefreshScope public class TestController { @Value("${testStr}") private String testStr; @GetMapping("/test") public String test() { return testStr; } }
注意看註釋;
bootstrap.yaml:
#bootstrap.yaml檔案一般,用來儲存最先啟動的配置變數 #其中spring.application.name要和nacos配置中心的dataId是一致的 spring: application: name: configdemo cloud: nacos: config: server-addr: localhost:8848 file-extension: yaml
啟動nacos:
之後,啟動專案,訪問:localhost:8080/test:
以上;