nacos 支持配置文件的公共配置内容共享。
已经完成的配置。
第一步 创建配置文件
新建配置文件。
配置文件中的填写内容
这是已经发布过的版本,才会出现 md5 ;第一次发布不会有。
第二步 拉取配置文件
SPRING BOOT 项目启动上下文 |
启动 |
V |
加载 |
applicatin.yml |
V |
初始化 |
ApplicationContext |
这是经典的 Spring Boot 项目启动的过程。
配置了 NACOS 之后,拉取文件和启动过程都会发生变化。
SPRING. CLOUD | SPRING BOOT |
启动 | -- |
V | V |
加载 | 加载 |
bootstrap.yml | applicatin.yml |
V | V |
拉取 NACOS 配置 | 合并配置 |
V | V |
初始化 | 初始化(完成) |
ApplicationContext | ApplicationContext |
第一 引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
alibaba-nacos-config 是完成nacos配置的识别。
bootstrap 是完成对 bootstrap.yml 配置文件的启动识别。
第二 bootstrip.yml
spring:
application:
name: shoppingservice # 微服务的名字
profiles:
active: local
cloud:
nacos:
discovery:
server-addr: ${baijing.spring.cloud.nacos.server-addr}
config:
file-extension: yml
shared-configs:
- data-id: public.jdbc.yml
- data-id: public.logging.yml
- data-id: public.swagger.yml
- data-id: public.connectionpool.yml
config: 和 NACOS 中配置的文件名与文件格式一致。
第三
通过配置文件能直接启动「微服务模块」即可。
这是 nacos 的读取示例代码,在截图能看到「示例代码」就是了。
// Refer to document: https://github.com/nacos-group/nacos-examples/tree/master/nacos-spring-boot-example/nacos-spring-boot-config-example
package com.alibaba.nacos.example.spring.boot.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
@Controller
@RequestMapping("config")
public class ConfigController {
@Value("${useLocalCache:false}")
private boolean useLocalCache;
public void setUseLocalCache(boolean useLocalCache) {
this.useLocalCache = useLocalCache;
}
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}
后续: