微服务从nacos配置中心获得配置信息
作者:互联网
一,安装nacos, 略
二,创建父工程和微服务工程 service1, service2,以idea为例
1, new -> project -> Maven -> 填写groupid等信息 -> finish
2,new -> module -> Maven -> 填写ArtifactId -> finish
三,父工程pom.xml中加入版本控制 (因为用到了spring-cloud, spring-cloud-alibaba, spring-boot相关的包)
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.2.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.1.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
四,service1, service2加入依赖(因为都是springboot应用,且都是用nacos作为配置中心)
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> </dependencies>
五,实现service1, service2(此处以service1为例)
1,编写启动类
@SpringBootApplication public class Service1Application { public static void main(String[] args) { SpringApplication.run(Service1Application.class, args); } }
2,配置bootstrap.yml (nacos作为配置中心使用时,配置信息应写在bootstrap.yml文件中,而非application.yml)
server: port: 8081 spring: application: name: service1 cloud: nacos: config: server-addr: 172.0.0.1:8848 namespace: c22e5019-0bee-43b1-b80b-fc0b9d847501 file-extension: yaml group: NACOS-CONFIG
3,写controller,从nacos获取配置信息
@RestController @RequestMapping("/demo") public class DemoController { //动态更新需要用到这个对象 @Autowired private ConfigurableApplicationContext applicationContext; //直接通过@Value注解就能获取nacos配置中心的数据,但这种写法不能实现动态更新 @Value(value = "${name}") private String name; @GetMapping("/test") public String test(){ return "test " + applicationContext.getEnvironment().getProperty("name"); } }
注:
//@NacosValue注解按字面理解,应该此注解就实现了动态更新,但经测试取到数据为null,不知是因为pom中引入的是sping-cloud依赖的原因还是其它原因,待确定! @NacosValue(value = "${name}", autoRefreshed = true)
标签:服务,name,spring,配置,nacos,pom,service1,cloud 来源: https://www.cnblogs.com/dongbo/p/12206016.html