[java]微服务架构连载No7 配置中心Config

来源:互联网 发布:试客联盟软件 编辑:程序博客网 时间:2024/06/04 01:13

配置中心:为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持, 包括环境,动态配置...

工程结构  spring-cloud-06-config-server  配置中心

spring-cloud-06-config-client  微服务


spring-cloud-06-config-server  配置中心

第一步: pom.xml 导入相关依赖

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


第二步: (1) 配置端口 7001

     (2) 配置git 地址: https://gitee.com/zhouguang666/springconfig

spring:  application:    name: config-server  cloud:    config:      server:        git:          uri: https://gitee.com/zhouguang666/springconfig   #相当prefix#          search-paths:#            - /user-service  # 相对路径#            - /role-serviceserver:  port: 7001  context-path: /

git 地址目录结构如下:


config_client-dev.properties 内容

from=git-dev

config_client.properties 内容

from=git-default


第三步: 开启配置中心

@EnableConfigServer //开启配置中心@SpringBootApplicationpublic class ServerApplication {    public static void main(String[] args) {        SpringApplication.run(ServerApplication.class, args);    }}

spring-cloud-06-config-client  微服务

第一步: 导入相关依赖

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


第二步: 配置文件 bootstrap.yml

(1) 端口 7002

(2)  指向配置中心 7001 端口

注意: application.name +"-"+ config.profile  = git上配置文件名, spring约定大于配置, 不能随便写,要保持一致

        (3)关闭自动刷新权限验证 security.enabled, 保证手动自动刷新接口 /refresh 不需要用户密码 

spring:  application:    name: config_client  cloud:    config:      uri: http://localhost:7001/ ## 表示配置中心地址      profile: dev  # 环境      label: master # 分支server:  context-path: /  port: 7002management:  security:    enabled: false   # spring 安全验证 , fasle:自动刷新不用输入密码

第三步:开启springboot 项目配置

@SpringBootApplicationpublic class ClientApplication {    public static void main(String[] args) {        SpringApplication.run(ClientApplication.class, args);    }}

第四步:  (1) 配置自动刷新作用域

      (2) 使用配置文件属性 from

@RefreshScope //动态刷新 >刷新作用域@RestControllerpublic class FromController {    @Value("${from}")    private String from;    @GetMapping("/from")    public String from(){        return "from is :"+from;    }}

期望结果

截图 1: 调用服务 http://localhost:7002/from  返回 from值 为  git-dev

截图2: 修改 git 配置文件config_client-dev.properties  from=git-dev-0.1 并提交

截图2: 调用自动刷新接口 http://localhost:7002/refresh 刷新配置

截图4: 调用服务 http://localhost:7002/from  返回 from值 为  git-dev-0.1


截图1:


截图2:



截图3



截图4:



阅读全文
0 0