Spring Cloud Config配置中心的使用

1、概述

1. 为何使用?git

  1> 配置文件太多,不方便维护spring

  2> 配置文件通常都保存这各类明文显示的密码,没法保证配置内容的安全性,也没法作到按权限分配给我的bootstrap

  3> 更新配置项目需重启,试想一想,在生产环境,那么多台机器。。。缓存

2. config介绍
config分为Server端和Client端,实现原理以下图所示:安全

  • Server端负责从远端git(码云、GitHub等)拉取配置,并缓存在本地;
  • Client端(上图的product和order服务)在启动时,从Server端本地缓存中获取配置

2、Server端配置

1. 新建config Server模块,加载依赖app

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

2. 在启动类上@EnableConfigServer注解,开启configServerpost

@EnableConfigServer //开启configServer
@SpringBootApplication
@EnableDiscoveryClient //开启Eureka Client
public class TestConfigApplication {

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

3. 在远端git上新建项目(这里使用码云),并把配置上传上去,具体操做略测试

说明:config语法规定,xxx.yml为公共配置,在拉取配置时会和xxx.{}profiles}.yml合并url

4. 修改配置文件spa

spring:
  application:
    name: test-config
  profiles:
    active: dev
#配置中心 cloud: config: server: git: uri: https:
//gitee.com/wslook/test-config-repo.git search-paths: user  //配置文件目录,多个用逗号隔开 username: xxx password: xxx default-label: master basedir: ./configRepo/  //本地缓存地址 force-pull: true  //强制拉取配置,解决手动修改本地缓存配置后,没法拉取最新配置的问题
# 注册中心
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:2181/eureka/
 

5. 测试

3、Client端配置

1. 加载依赖

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

2. 修改配置文件(把配置文件名改成bootstrap.yml)

spring:
# 配置中心
  cloud:
    config:
     name: user-config
     profile: dev
     label: master
     discovery:
        enabled: true
        serviceId: test-config
     fail-fast: true


# 注册中心
eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://localhost:2181/eureka/

3. 测试

编写测试代码:

@RequestMapping("/test")
@RestController
public class TestController {

    @Resource
    private OSSProperties ossProperties;

    @RequestMapping("/config")
    public String test(){
        return ossProperties.getUrl();
    }
}

启动user服务,能够看到,已经把配置拉取下来了

使用postman验证

 

4、高可用

对于config集群,很简单,由于由注册中心(这里使用的eureka)统一管理服务,因此不须要额外的配置,只需多启动几台config Server服务便可

相关文章
相关标签/搜索