52 Spring Cloud Config入门

准备工作

Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置, 默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储。这里使用git作为学习的环境

使用GitHub时,国内的用户经常遇到的问题是访问速度太慢,有时候还会出现无法连接的情况。如果我 们希望体验Git飞一般的速度,可以使用国内的Git托管服务——码云(gitee.com)。和GitHub相比, 码云也提供免费的Git仓库。此外,还集成了代码质量检测、项目演示等功能。对于团队协作开发,码 云还提供了项目管理、代码托管、文档管理的服务。

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

image-20220102210211739.png

(2)创建项目config-repo

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

image-20220102210244308.png

文件命名规则:

{application}-{profile}.yml

{application}-{profile}.properties

application为应用名称 profile指的开发环境(用于区分开发环境,测试环境、生产环境等)

搭建服务端程序

(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);
 }
}

@EnableConfigServer : 通过此注解开启注册中心服务端功能

(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.config.server.git.username: 配置git用户名
  • 通过spring.cloud.config.server.git.password: 配置git密码

(4) 测试

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

image-20220102210536299.png

修改客户端程序

(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

image-20220102210728217.png

对应的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提交,查看数据已经发生了变 化

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容