一,安裝nacos, 略web
二,建立父工程和微服務工程 service1, service2,以idea爲例spring
1, new -> project -> Maven -> 填寫groupid等信息 -> finishbootstrap
2,new -> module -> Maven -> 填寫ArtifactId -> finishspringboot
三,父工程pom.xml中加入版本控制 (由於用到了spring-cloud, spring-cloud-alibaba, spring-boot相關的包)app
<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做爲配置中心)ide
<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爲例)spring-boot
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獲取配置信息idea
@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)