SpringCloud + SpringBoot 整合Nacos作配置中心 【二】
原创
©著作权归作者所有:来自51CTO博客作者wx6316c4e40e2ec的原创作品,请联系作者获取转载授权,否则将追究法律责任
新建配置



创建服务
1.引入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
2、创建配置文件名为bootstrap.yml,注意是bootstrap.xxx,而不是application或者其他。原因如下
Nacos同springcloud-config一样,在项目初始化时,要保证先从配置中心进行配置拉取,拉取配置之后,才能保证项目的正常启动。springboot中配置文件的加载是存在优先级顺序的,bootstrap优先级高于application
spring:
application:
#服务名称
name: nacos-config
cloud:
nacos:
discovery:
#连接注册中心 指定注册中心的地址,如果你不需要注册该服务,也可以去掉该项,
server-addr: 192.168.230.136:8848
#连接配置 指定配置中心的地址
config:
server-addr: 192.168.230.136:8848
file-extension:
启动类加注解:
package com.fh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConfigApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConfigApplication.class, args);
}
}
创建控制层进行测试
package com.fh.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("config")
@RefreshScope //使当前类下的配置支持动态更新
public class NacosConfigController {
@Value("${nacos.config}") //读取key为nacosconfig的配置的值
private String config;
@RequestMapping("/getValue")
public String getValue() {
return config;
}
}
在浏览器访问 http://localhost:10002/config/getValue
效果1:

效果2:

值来源:

此时说明已经成功读取到配置,下面我将Nacos-Server上的配置修改为bacos,看看能否动态更新,如下图:
