SpirngCloud(六)之走进Spring Cloud Config

458 阅读2分钟

这是我参与8月更文挑战的第31天,活动详情查看:8月更文挑战

介绍

服务器为外部配置(名称值对或等效的YAML内容)提供了基于资源的HTTP。它包含了Client和Server两个部分,server提供配置文件的存储、以接口的形式将配置文件的内容提供出去,client通过接口获取数据、并依据此数据初始化自己的应用。

功能分类

 Server功能

  • 用于外部配置的HTTP,基于资源的API
  • 加密和解密属性值(对称和非对称)
  • 使用可嵌入Spring Boot应用程序
  • 结合Eureka实现高可用
  • 结合Spring Cloud Bus实现自动化持续集成

Client功能(适用于Spring应用程序)

  • 绑定到Config Server并Environment使用远程属性源初始化Spring
  • 加密和解密属性值(对称和非对称)
  • 结合Eureka实现服务发现

Maven依赖

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

SpringCloud Config 示例

服务端

首先需要搭建一个服务注册中心

我在git上配置了3个运行环境的yml配置文件。 image.png

image.png

代码

spring.application.name=springcloud-hystrix-eureka-server
server.port=9001
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

启动类

@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
public class ConfigServer3344Application {

	public static void main(String[] args) {
		SpringApplication.run(ConfigServer3344Application.class, args);
		System.out.println("配置中心服务端启动成功!");
	}
}

application.yml中的配置

spring:
  application:
    name: cloud-config-center
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/xxx/xxxxx.git #码云上面的git仓库的名称
          username: #git仓库的账号。
          password: #git仓库的密码。
          ####搜索目录
          search-paths:
            - 你的文件目录   #git仓库地址下的相对地址 多个用逗号","分割
      ###读取的分支
      label: master

客户端

bootstrap.yml配置

spring:
  application:
    name: config-client
  cloud:
    config:
      label: master #分支名称
      name: config #配置文件名称
      profile: dev #读取后缀名称    上述三个综合:master分支上的config-dev.yml的配置文件被读取http;//config3344.com:3344/master/config-dev.yml
      uri: http://localhost:3344 #配置中心的地址

启动类

@EnableDiscoveryClient
@SpringBootApplication
public class ConfigClient3355Application {

    public static void main(String[] args) {
        SpringApplication.run(ConfigClient3355Application.class, args);
        System.out.println("配置中心客户端启动成功!");
    }
}

测试代码

@RestController
@RefreshScope
public class ConfigClientroller {

    @Value("${config.info}")
    private String configInfo;

    @GetMapping("/configInfo")
    public String getConfigInfo(){
        return configInfo;
    }
}

总结

在尤其是一个变动多个服务都需要变动的时候就大大的增加了维护的成本,对维护也是及其不友好的。如果所有的配置都写在配置文件里面,这样的话对代码的安全性也有一定的挑战。使用了Spring Cloud Config可以减少一些公共的配置的编写,也降低了维护的成本,安全性也得以提升。

手写不易,还需大家多多点赞和专注,喜欢技术的同学们不要心急,此系列文章我将逐步推出,我们大家一起学习。