微服务框架——SpringCloud(四)
1.Spring Cloud Config 分布式配置
a.Config服务器
①新建springboot项目,依赖选择Config Server
②pom文件关键依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> ...... </dependencies> ......
③application.yml文件
spring: application: name: config-server profiles: #配置文件在本地 active: native #配置文件的目录 cloud: config: server: native: search-locations: classpath:/config server: port: 8101
④启动类添加注解@EnableConfigServer
@SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
⑤在resources下新建config/commom-dev.properties,用于测试
test.name=vettel
test.password=111111
⑥启动后访问 http://localhost:8101/common/dev 可查看配置文件信息,访问路径有如下几种
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
注:对于resources下的config/commom-dev.properties,{application}为文件名"commom",{profile}为环境名"dev",{label}为路径名"config"。
b.Config客户端
①新建springboot项目,依赖选择 Config Client 、Web
②pom文件关键依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> ...... </dependencies> ......
③bootstrap.yml文件
spring: application: name: config-client cloud: config: uri: http://localhost:8101 profile: dev name: common server: port: 8102
注意:此处需要将配置写入bootstrap.yml(会优先于application.yml加载)中,因为config的配置是优先于application.yml加载的,否则会报错。
④具体使用
@SpringBootApplication @RestController public class ConfigClientApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); } @Value("${test.name}") String name; @Value("${test.password}") String password; @RequestMapping(value="/getConfig") public String getConfig(){ return "name[" + name + "], password[" + password + "]"; } }