Spring Cloud 组件4

spring cloud config

简介

Spring Cloud Config为分布式系统中的外部化配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring Environment和PropertySource抽象,因此它们非常适合Spring应用程序,但可以与任何语言运行的任何应用程序一起使用。当应用程序通过部署管道从开发到测试并进入生产时,您可以管理这些环境之间的配置,并确保应用程序具有迁移时需要运行的所有内容。服务器存储后端的默认实现使用git,因此它可以轻松支持配置环境的标签版本,以及可用于管理内容的各种工具。添加替代实现并使用Spring配置插入它们很容易。

Spring Cloud Config Server功能

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

Config Client功能

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

搭建服务端

  1. 新建Spring Boot项目 configserver

  2. 引入主要依赖 spring-cloud-config-server

     <dependency>
     	 <groupId>org.springframework.cloud</groupId>
     	  <artifactId>spring-cloud-config-server</artifactId> 
     </dependency>
    
  3. 引入 spring-boot-starter-web

     <dependency> 
     	<groupId>org.springframework.cloud</groupId>
     	 <artifactId>spring-boot-starter-web</artifactId> 
     </dependency>
    
  4. 主程序添加注释 @EnableConfigServer

     @SpringBootApplication 
     @EnableConfigServer 
     public class ConfigserverApplication { 
     	public static void main(String[] args) {
     	 	SpringApplication.run(ConfigserverApplication.class, args);
     	 	 }
      }
    
  5. 设置属性
    这里使用 .properties 的方式进行配置。你可以自行更换为同等效果的 .yml 方式。配置信息需要放在 bootstrap.properties 中。
    1)Git方式存储配置文件示例
    #配置文件存放在Git的情况 spring.cloud.config.server.git.uri=http://你的ip:你的端口号/***/*.git spring.cloud.config.label=master spring.cloud.config.server.git.search-paths=/ spring.cloud.config.server.git.username=username
    spring.cloud.config.server.git.password=password
    2)本地存储配置文件
    #配置文件存放在本地的情况 #注意:文件夹要有访问权限 spring.profiles.active=native spring.cloud.config.server.native.search-locations=本地地址

客户端配置

pom.xml

在pom.xml 文件中引入config 依赖

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

bootstrap.properties

在resources 目录下创建一个 bootstrap.properties 文件,至于为什么要是这个而不是application.properties 文件,是由加载机制决定的,加载的时候会先加载bootstrap.properties 文件,然后加载application.properties ,文件内容如下:

spring.application.name=自定义的名
spring.cloud.config.profile=eurekaserver
spring.cloud.config.label=master
spring.cloud.config.uri=http://localhost:9008/

发布了12 篇原创文章 · 获赞 0 · 访问量 260

猜你喜欢

转载自blog.csdn.net/qq_41970133/article/details/104102742