spring-cloud-demo-02-config
本Demo演示了Config服务端的搭建,以及客户端如何通过Config服务端获取配置文件。
源码:https://github.com/seepine/spring-cloud-demo
模块介绍
spring-cloud-demo-02-config模块分为两个子模块,分别为Config-Server(Config服务端)和Config-Client(Config客户端)。
一、搭建Config服务端
1.Config-Server
1.1 添加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
|
1.2 在启动类上添加注解@EnableConfigServer
1 2 3 4 5 6 7 8 9
| @EnableConfigServer @SpringBootApplication public class SpringCloudDemo02ConfigServerApplication {
public static void main(String[] args) { SpringApplication.run(SpringCloudDemo02ConfigServerApplication.class, args); }
}
|
1.3 添加配置文件
1 2 3 4 5 6 7 8 9 10
| spring: application: name: config-server cloud: config: server: git: uri: https://github.com/seepine/spring-cloud-demo-config server: port: 10000
|
1.4 创建git配置文件仓库(可参考https://github.com/seepine/spring-cloud-demo-config)
创建文件名为config-client-dev.yml
1 2 3
| user: username: seepine password: 123456
|
1.5 启动ConfigServer并验证
输入地址及文件名:http://127.0.0.1:10000/config-client-dev.yml
2.Config-Client
2.1 添加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
|
2.2 添加配置文件
1 2 3 4 5 6 7 8 9 10
| spring: application: name: config-client cloud: config: uri: http://localhost:10000 profiles: active: dev server: port: 11000
|
2.3 创建两个获取配置文件值的实体类
1 2 3 4 5 6 7 8
| @Data @Component public class User { @Value("${user.username}") private String username; @Value("${user.password}") private String password; }
|
1 2 3 4 5 6 7
| @Data @Component @ConfigurationProperties(prefix = "user") public class UserConfig { private String username; private String password; }
|
2.4 编写测试接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @RestController @AllArgsConstructor public class ApiController { private User user; private UserConfig userConfig;
@GetMapping("/user") public Object getUser() { return user; } @GetMapping("/user/config") public Object getUserConfig() { return userConfig; } }
|
2.5 分别测试两个接口
3.整合Eureka
3.1 Config-Server与Config-Client添加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
|
3.2 Config-Server与Config-Client添加配置
1 2 3 4 5 6
| eureka: instance: hostname: localhost client: service-url: defaultZone: http://seepine:123456@${eureka.instance.hostname}:8761/eureka/
|
3.3 Config-Server配置文件修改
1 2 3 4
| discovery: enabled: true service-id: CONFIG-SERVER
|
3.4 重启客户端分别测试两个接口