spring cloud config分布式配置中心

分布式系统中,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件springCloud Config ,它支持从远程Git仓库中读取配置文件并存放到本地Git仓库。

基本原理
git 上存放我们的远程配置文件
config-server 连接到 git
config-client 连接到config-server
当我们启动config-client 服务的时候,client 会通过连接的 config-server 拿到远程git 上面的配置文件,然后通过 Spring 加载到对象中。


config-server


创建子模块config-server-demo,在pom.xml中导入依赖

<dependencies>   
    <!--spring cloud config 服务端依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>

创建启动类 ConfigServerApp

@SpringBootApplication
//开启configserver注解
@EnableConfigServer
public class ConfigServerApp {

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

创建application.yml

###服务端口号
server:
  port: 9100

###服务名称(服务注册到eureka名称)
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          ###github仓库地址
          uri: git@github.com:GitHub6ms/config-server-demo.git
          ###代表上面仓库下的所有文件
          search-paths: /**
          ###仓库设置为公开的所以不用账号密码
          username:
          password:
      ###哪个分支,master主分支
      label: master

在github中创建config-demo-dev.properties文件 内容随便
文件名命名规范:
文件名-环境名.后缀
启动后访问地址为:
1.localhost:9100/config-demo/dev
2.localhost:9100/config-demo-dev.properties
3.localhost:9100/master/config-demo-dev.properties


config-client


创建子模块config-client-demo,在pom.xml中导入依赖

 <dependencies>
        <!--spring cloud config 客户端依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <!--web的依赖,必须加-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

新建启动类ConfigClientApp

 @SpringBootApplication

public class ConfigClientApp {

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

新建controller类

@RestController
public class TestController {

    //读取配置文件中的email
    @Value("${email}")
    private String email;


    /**
     * 返回配置文件中的值
     *
     */
    //访问value
    @GetMapping("/value")
    @ResponseBody
    public String returnValue(){
        return email;
    }
}

新建配置文件application.yml

 ###服务端口号
server:
  port: 9201

###服务名称(服务注册到eureka名称)
spring:
  application:
    name: hello-config

  cloud:
    config:
      ###config server的uri
      uri: http://localhost:9100/
      ###指定环境
      profile: dev
      ###指定分支
      label: master

访问
localhost:9201/value

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值