项目中使用方式
第一步 增加依赖
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.8</version>
</dependency>
第二步 增加配置
在application.yaml中增加配置
测试环境
nacos:
config: # 这里的优先级高于扩展配置ext-config:
bootstrap:
enable: true #开启配置预加载功能
log-enable: false
server-addr: https://nacos.test.com # 主配置服务器地址
group: ${spring.profiles.active} # 主配置 group-id 这里约定环境参数
namespace: namespace-jc # 主配置
data-id: aa-boot # 主配置 data-id
type: yaml # 主配置 配置文件类型
remote-first: true # true 代表nacos配置中心的配置优先级高 否则本地配置优先级高 默认false
max-retry: 2 # 主配置 最大重试次数
auto-refresh: true # 主配置 开启自动刷新
config-retry-time: 3000 # 主配置 重试时间
config-long-poll-timeout: 6000 # 主配置 配置监听长轮询超时时间
enable-remote-sync-config: false # 主配置 开启注册监听器预加载配置服务(除非特殊业务需求,否则不推荐打开该参数)
username: guest
password: xx
这里可以使用扩展配置这里不展开 如果想使用 可以参考文末例子
生产环境
在测试环境的基础上增加配置
application-prod.yaml
nacos:
config:
server-addr: http://nacos-hs.namespace.svc.cluster.local:8848 #k8s内网访问
namespace: 填写你的名称空间ID # 请用 guest/xxx账号查看 如下图
username: guest
password: xx
灰度环境
在测试环境的基础上增加配置
application-gray.yaml
nacos:
config:
server-addr: https://nacos.pro.com
namespace: 854eabfb-8fa0-489a-9e9b-261477592d5b # 登录后台查看自己所属的名称空间的ID 请用 guest/xxx账号查看 如下图
username: guest
password: xx
第三步 增加配置类
方式一 配置类
package org.example.config;
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
import lombok.Data;
import org.springframework.context.annotation.Configuration;
/**
* 这种配置 在没有知道namespace下 默认是 nacos.config.namespace
* 如果使用这种方式一定要找准dataid的位置坐标
*/
@NacosConfigurationProperties(dataId = "wholion-boot", type = ConfigType.YAML, autoRefreshed = true, prefix = "guest", properties = @NacosProperties(namespace = "public"))
@Data
@Configuration
public class UserProperties {
private String name;
private String gender;
}
方式二
@RestController
@Slf4j
public class UserController {
@Resource
private UserRepository userRepository;
@Resource
private UserProperties userProperties;
@NacosValue(value = "${guest.name:none}",autoRefreshed = true)
private String name;
// 自动刷新有两种方式
@NacosValue(value = "${guest.gender:none}", autoRefreshed = true)
private String gender;
@Resource
private StringRedisTemplate stringRedisTemplate;
@RequestMapping(value = "/hi")
String hi() {
StopWatch stopWatch = new StopWatch("s");
stopWatch.start("redis");
String s = stringRedisTemplate.opsForValue().get("mc:mc:code");
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
log.info("instance {} ", this);
return "Hi " + userProperties.getName() + " " + userProperties.getGender() +s;
}
@RequestMapping(value = "/hello")
String hello() {
log.info("instance {} ", this);
return "Hello " + name + " " + gender;
}
}
第三步 nacos增加配置 启动即可访问
更多高级用法
参考例子
官网参考