Loading

Spring Cloud Config入门

准备工作

Confifig Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储。这里使用git作为学习的环境
 
使用GitHub时,国内的用户经常遇到的问题是访问速度太慢,有时候还会出现无法连接的情况。如果我们希望体验Git飞一般的速度,可以使用国内的Git托管服务——码云(gitee.com)。和GitHub相比,码云也提供免费的Git仓库。此外,还集成了代码质量检测、项目演示等功能。对于团队协作开发,码云还提供了项目管理、代码托管、文档管理的服务。

(1)浏览器打开gitee.com,注册用户 ,注册后登陆码云管理控制台

(2)创建项目config-repo仓库

1,2略

(3)上传配置文件,将product_service工程的application.yml改名为product-dev.yml后上传

文件命名规则:
  {application}-{profifile}.yml
  {application}-{profifile}.properties
  application为应用名称 profifile指的开发环境(用于区分开发环境,测试环境、生产环境等)

搭建服务端程序

(1) 引入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

(2) 配置启动类

@SpringBootApplication
@EnableConfigServer //开启配置中心服务端功能
public class ConfigServerApplication {
 public static void main(String[] args) {
 SpringApplication.run(ConfigServerApplication.class, args);
 }
}
@EnableConfifigServer : 通过此注解开启注册中心服务端功能

(3) 配置application.yml 

server:
 port: 10000 #服务端口
spring:
 application:
   name: config-server #指定服务名
 cloud:
   config:
     server:
       git:
         uri: https://gitee.com/it-lemon/config-repo.git
通过 spring.cloud.config.server.git.uri : 配置git服务地址
通过`spring.cloud.confifig.server.git.username: 配置git用户名
通过`spring.cloud.confifig.server.git.password: 配置git密码

(4) 测试

启动此微服务,可以在浏览器上,通过server端访问到git服务器上的文件

修改客户端程序

(1) 引入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

(2) 删除application.yml

springboot的应用配置文件,需要通过Config-server获取,这里不再需要。

(3) 添加bootstrap.yml

使用加载级别更高的 bootstrap.yml 文件进行配置。启动应用时会检查此配置文件,在此文件中指定配置中心的服务地址。会自动的拉取所有应用配置并启用 
spring:
 cloud:
   config:
     name: product
     profile: dev
     label: master
     uri: http://localhost:8080

手动刷新

我们已经在客户端取到了配置中心的值,但当我们修改GitHub上面的值时,服务端(Config Server)能实时获取最新的值,但客户端(Config Client)读的是缓存,无法实时获取最新值。SpringCloud已经为我们解决了这个问题,那就是客户端使用post去触发refresh,获取最新数据,需要依赖spring-boot-starter-actuator 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
对应的controller类加上@RefreshScope
@RefreshScope
@RestController
public class TestController{
    @Value("${productValue}")
    private String productValue;
    /**
     * 访问首页
     */
    @GetMapping("/index")
    public String index(){
        return "hello springboot!productValue:" + productValue;
   }
}
配置文件中开发端点 
management:
 endpoints:
   web:
     exposure:
       include: /bus-refresh
在postman中访问http://localhost:9002/actuator/bus-refresh,使用post提交,查看数据已经发生了变化 
posted @ 2021-07-29 15:42  1640808365  阅读(74)  评论(0编辑  收藏  举报