配置一个ConfigClient
- config-service服务已经可以从git远程仓库获取到对应的配置文件,这个时候我们继续集成,启用模块从config-service中获取配置文件
- 在user_service服务模块中导入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
- 添加bootstrap.yml配置文件,该配置文件优先级较高,会读取config-service的配置信息到allpication.yml中,并且先把application.yml的数据清空
spring: cloud: config: name: userservice # 配置文件的名称 profile: dev # 环境 label: master # 分支 discovery: enabled: true # 通过注册中心寻找ConfigServer service-id: config-server # ConfigServer的服务id eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka/
- 为了方便测试,创建一个测试类获取配置文件的信息
@Data @Component @ConfigurationProperties(prefix = "test.redis")//读取配置文件的属性配置 public class RedisProperties { private String host; private Integer port; }
- 创建一个controller,调用测试类的数据
@RestController @RequestMapping("hello") public class RedisController { @Autowired private RedisProperties redisProperties; @GetMapping("redis") public RedisProperties getRedisProperties(){ return redisProperties; } }
- 页面访问:http://127.0.0.1:8081/hello/redis
手动刷新服务的配置信息
- 当我们修改了git的配置文件信息后,只能同步修改config-service的配置信息,但是单个服务的配置信息并没有立刻修改,这里我们继续集成,实现手动修改
- 在user_service中引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
- 在bootstrap.yml文件中加入以下配置,用来暴露刷新接口
spring: cloud: config: name: userservice # 配置文件的名称 profile: dev # 环境 label: master # 分支 discovery: enabled: true # 通过注册中心寻找ConfigServer service-id: config-server # ConfigServer的服务id eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka/ management: endpoints: web: exposure: include: "*" # 暴露refresh接口
- 测试
- 我们手动修改git的配置文件信息,访问http://127.0.0.1:8081/hello/redis后发现服务的配置信息并没有修改,
- 此时使用zpizz调用接口http://localhost:8081/actuator/refresh,注意:是post无参方式
- 刷新后再次调用http://127.0.0.1:8081/hello/redis检查即可