SpringCloud学习(四) Config Server将配置文件配置在本地仓库并刷新

Config Server将配置文件配置在本地仓库并刷新

spring cloud官方建议将配置文件配置在远程git仓库,我们某些时候可能想将配置文件放在本地的仓库。这里使用最新cloud版本Finchley.RELEASE做测试。

服务端配置
1 创建本地git仓库,存入几个配置文件,configlearn-client-.properties,configlearn-client-dev.properties,configlearn-client-xxx.properites等等。git init ,git add . git commit ,将这些git提交到本地仓库,git不懂可以参见之前的文章https://blog.csdn.net/u011943534/article/details/80783789
2 configserver模块引入依赖,springcloud其他依赖引入不介绍了,可参见官方文档

compile('org.springframework.cloud:spring-cloud-config-server')

3 启动类添加注解@EnableConfigServer

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApp {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(ConfigServerApp.class);
        application.run(args);
    }
}

4 重点来了 application.properties配置,git.uri配置方式不用http开头而是使用本地文件协议,file:///方式,地址指向第一步创建的git仓库地址

server.port=10001
spring.application.name=configlearn-server
spring.cloud.config.server.git.uri=file:///E:/coding/git/localRep/configlearn

5 访问http://localhost:10001/configlearn-dev.properties,可以看到能够显示configlearn-dev.properties的内容,服务端就配置成功了。

客户端配置
1 创建客户端模块,引入依赖

compile('org.springframework.cloud:spring-cloud-starter-config')

2 配置bootstrap.properties,这里必须使用bootstrap,他的加载顺序优先于application.properties。spring.cloud.config.label指向git仓库的分支名;spring.cloud.config.profile指向active的文件,这里就是{spring.application.name}-{profile},也就是configlearn-client-dev.properties,一定要保证git仓库有这个配置,不然启动会出错;spring.cloud.config.uri指向configserver地址。

spring.application.name=configlearn-client
server.port=10002
spring.cloud.config.profile=dev
spring.cloud.config.label=master
spring.cloud.config.uri=http://localhost:10001
management.endpoint.env.enabled=true
management.endpoints.web.exposure.include=*

3 为了方便查看配置结果,创建一个接口获取配置文件的数据

@SpringBootApplication
@RestController
public class ConfigClientApp {
    @Value("${profile}")
    private String profile;
    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApp.class, args);
    }
    @GetMapping("/get")
    public String get(){
        return profile;
    }
}

4 访问http://localhost:10002/get会发现返回了配置文件对应的配置。


Bean刷新
第一种方式手动刷新
在要刷新的类上配置标记@RefreshScope,post方式调用http://localhost:10002/actuator/refresh,如果springboot是2以下的版本没有/actuator
第二种方式定时刷新
通过@Autowired注入ContextRefresher,作一个定时任务,定时调用contextRefresher.refresh()。


@Component
public class Sche {
    @Autowired
    private ContextRefresher contextRefresher;
    @Scheduled(fixedRate = 5000, initialDelay = 3*1000)
    public void refresh(){
        Set<String> result = contextRefresher.refresh();
        System.err.println(result);
    }
}

第三种方式bus总线刷新以及git webhook方式以后有机会介绍

github 源码
上一篇 SpringCloud学习(三) springcloud finchley爬坑记

猜你喜欢

转载自blog.csdn.net/u011943534/article/details/80960475
今日推荐