环境
nacos版本: NACOS1.4.0 具体怎么安装nacos,百度一下即可。
依赖
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE
com.example
nacos
0.0.1-SNAPSHOT
nacos
Demo project for Spring Boot
1.8
2.2.5.RELEASE
UTF-8
org.springframework.cloud
spring-cloud-dependencies
Hoxton.RELEASE
pom
import
com.alibaba.cloud
spring-cloud-alibaba-dependencies
${spring-cloud-alibaba.version}
pom
import
org.springframework.boot
spring-boot-starter-web
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config
${spring-cloud-alibaba.version}
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
${spring-cloud-alibaba.version}
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
本地配置
spring:
application:
# 应用名称
name: nacos-test
cloud:
nacos:
config:
# 设置配置中心服务端地址
server-addr: 192.168.1.20:8848
file-extension: yaml
# 文件前缀
prefix: test
# 命名空间ID
namespace: b53ece8f-3e05-473a-b141-e8d066ef3998
discovery:
# nacos注册中心地址
server-addr: 192.168.1.20:8848
namespace: b53ece8f-3e05-473a-b141-e8d066ef3998
#register-enabled: false 只从注册中心获取服务而不将自己注册
#开启包日志
logging:
level:
com.example.nacos: debug
#设置监听端口
server:
port: 8001
启动类
@SpringBootApplication
//开启服务发现
@EnableDiscoveryClient
public class NacosApplication {
public static void main(String[] args) {
SpringApplication.run(NacosApplication.class, args);
}
}
相关类
package com.example.nacos.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import java.io.Serializable;
@Data
@Configuration
//添加这个配置就可以实时更新nacos的配置参数
@RefreshScope
public class CommonParameter implements Serializable {
@Value("${common.name}")
private String name;
@Value("${common.age}")
private Integer age;
@Value("${common.address}")
private String address;
}
测试类
package com.example.nacos.controller;
import com.example.nacos.config.CommonParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestParameter {
@Autowired
private CommonParameter commonParameter;
@GetMapping("test")
public String test(){
String str = "name:"+commonParameter.getName()
+ " age:"+commonParameter.getAge()
+ " address:"+commonParameter.getAddress();
return str;
}
}
nacos配置
common:
name: zhangsan
age: 444
address: street 555
测试
1.启动服务,查看nacos服务注册 2.使用浏览器测试 3.修改nacos配置,重新访问查看结果 查看服务器日志,看到配置信息已经被拉取下来。 浏览器访问: ok!至此,nacos的服务器注册与发现,动态配置及实时更新配置已经完成。 over!
前人少挖坑,后人少踩坑;前人记录,后人好踩坑;前人多种树,后人好乘凉
|