• Spring Cloud-config(十一)


    说明

    用于分布式中统一的配置管理,是一个单独的微服务

    简单例子

    准备git

    1.我自己在本地环境搭建了git服务器 也可以使用github 可参考:https://www.cnblogs.com/LQBlog/p/10218798.html    可参考git命令https://www.cnblogs.com/LQBlog/p/10219959.html

    2.添加一个git仓库 当前demo git地址为:http://admin@localhost:1234/r/config.git

    3在master分支增加2个配置文件

    内容分别为data-source:2   data-source:1

    4.再添加一个properti2.0 分支

    内容分别为data-source: properti2.0-i3  data-source:properti2.0.1

    服务端

    1.创建一个spring-cloud-config-server项目

    2.引入pom依赖

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

    3.启动添加config服务端功能

    @SpringBootApplication
    @EnableConfigServer //开启config服务端功能
    public class SpringCloudConfigApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringCloudConfigApplication.class, args);
        }
    
    }

    4.yml配置git信息

    spring:
      application:
        name: config
      cloud:
        config:
          server:
            git:
              uri: http://admin@localhost:1234/r/config.git #git地址
              search-paths: ERPApplicationConfig/ #查找git目录
              username: admin #git用户名
              password: admin  #git密码
    server:
      port: 7001
    

    5.访问配置文件的URl映射  

     /{application}/{profile}[/{label}]
    
    {application}-{profile}.yml
    
    /{label}/{application}-{profile}.yml
    
    /{application}-{profile}.properties
    
    /{label}/{application}-{profile}.properties

    如访问master dev环境的文件

    http://127.0.0.1:7001/mybatis/dev/master

    version为git上面的版本号   通过版本号可以知道返回的哪一次提交的配置

    server启动时会通过git clone 将配置信息复制一份到本地。然后每次访问http://127.0.0.1:7001/mybatis/dev/master 会通过git pull  获取最新配置。如果git 挂了 会直接返回本地的配置;如关掉git服务端再访问http://127.0.0.1:7001/mybatis/dev/master 日志打印

    虽然报错 但是还是能正常返回配置信息  因为返回本地的原因

    客户端

    1.新建一个client项目

    2.配置pom依赖

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

    3.新建一个bootstrap.yml 

    ps:因为读取配置的时候是加载bootstrap.yml的时候就读取了 如果配置到application.yml 加载的时候这个配置还没初始化

    spring:
      application:
        name: mybatis #对应{application}
      cloud:
        config:
          profile: dev #映射{profile}
          label: master #映射{label}
          uri: http://127.0.0.1:7001 #config server地址
    server:
      port: 7002

    4.新建一个contorller测试读取配置

    @Controller
    public class ConfigInfoContorller {
        @Value("${data-source}")
        private String dataSource;
        @RequestMapping("/getDataSorce")
        @ResponseBody
        public String getDataSource(){
            return dataSource;
        }
    }

    或者

    @Controller
    public class ConfigInfoContorller {
        @Autowired
        private Environment environment;
        @RequestMapping("/getDataSorce")
        @ResponseBody
        public String getDataSource() {
            //读取配置 如果不存在返回undefined
            return environment.getProperty("data-source", "undefined");
        }
    
    }

    5.启动config servicer  configclient测试

    更多配置

    本地调试

    当configserver服务不可用或者我们需要本地调试指定我们自己的配置文件 可以将配置git clone到本地 然后指定应用我们本地的配置

    spring:
      cloud:
        config:
          server:
            git:
              uri: file:/Users/liqiang/Desktop/gitblit/config/config 
              search-paths: ERPApplicationConfig/ #查找git目录

    uri占位符

    通过application自动映射仓库地址 实现一个项目对应一个git

    http://admin@localhost:1234/r/config.git

    http://admin@localhost:1234/r/{application} 

    当我们输入http://127.0.0.1:7001/config/dev/master  会自动把config 映射到对应的仓库地址  

    如果使用config client 会把application.name填充到占位符

    ps:不仅{application} 可以占位{profile}{label}也可以

    search-paths占位

    实现一个git 不同的项目对应不同的配置目录

    spring:
      application:
      cloud:
        config:
          server:
            git:
              uri: http://admin@localhost:1234/r/config #git地址   file:/Users/liqiang/Desktop/gitblit/config/config
              search-paths: '{application}/' #查找git目录
              username: admin #git用户名
              password: admin  #git密码

    将搜索appliction映射名字目录下的 application-profile文件

    多仓库配置

    容易造成混乱不推荐

    本地文件系统

    将应用本地文件 src/main/resource下的配置文件 不推荐使用 可以通过spring.cloud.config.server.native.search-locations指定搜索路

    spring.profiles.active= native

    健康监测

    http://admin@localhost:1234/r/{application}  当我们使用占位符的方式的时候server会去检查http://admin@localhost:1234/r/app的git地址 导致报错以及heath健康检查为dwon 导致分析的时候误认为git挂了

    测试

    1.server引入端点pom

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

    2.开启端点配置

    management:
      endpoints:
        web:
          exposure:
            include: health

    3、访问http://127.0.0.1:7001/actuator/health

    4.增加配置

    spring:
      application: config-server
      cloud:
        config:
          server:
            git:
              uri: http://admin@localhost:1234/r/{application} #git地址   file:/Users/liqiang/Desktop/gitblit/config/config
              search-paths: '{application}/' #查找git目录
              username: admin #git用户名
              password: admin  #git密码
            health:
              repositories:
                check:
                  name: config #检查的application占位符
                  lable: master #检查的lable占位符
                  profiles: default #检查的profiles 占位符
    server:
      port: 7001
    management:
      endpoints:
        web:
          exposure:
            include: health

    访问

    也可以通过

    spring.cloud.config. server.health.enabled=false关闭健康检查

    属性覆盖

    spring.cloud.config.server.overrides.{propertyname}={value} config-server通过此配置配置的属性将不可被客户端覆盖

    安全保护

    身份认证

    1.serverconfig增加pom依赖

      <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>

    2.serverconfig配置

    spring:
      security:
        user:
          name: liqiang
          password: liqiang

    3.访问http://127.0.0.1:7001/config/dev/master

     4.config-client客户端则需要配置

    spring:
      cloud:
        config:
          username: liqiang
          password: liqiang

    配置加密(对称加密)

    1.下载需要更换的jar http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

    2.执行java -verbose查看jdk安装 

    3.将下载下来的jar 覆盖$JAVA HOME/jre/lib/security 原来的jar

    4.server配置秘钥

    encrypt:
      key: ffff

    ps:必须在bootstrap下配置

    5.相关端点

    http://127.0.0.1:7001/encrypt/status(get请求) 返回ok表示配置成功

    http://127.0.0.1:7001/key(get请求) 返回秘钥

    http://127.0.0.1:7001/encrypt(post请求) 将body文件加密

    http://127.0.0.1:7001/decrypt(post请求) 将body文件解密

    6.使用posmanpost访问/encrypt 将加密数据放到body进行加密

    7.将配置信息的放入加密字符串并加上{cipher}前缀

    8.当客户端访通过config-server访问配置文件 cipher前缀的标识着加密数据 将自动解密

    配置中心集群

    传统方式

    服务端集群通过nginx代理

    注册中心服务化

    服务端

    1.pom增加eureka依赖

      <!--使用eureka来实现配置中心的高可用-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>

    2.application增加注解开启服务注册功能

    @SpringBootApplication
    @EnableConfigServer //开启config服务端功能
    @EnableDiscoveryClient //开启将服务注册到注册中心
    public class SpringCloudConfigServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringCloudConfigServerApplication.class, args);
        }
    
    }

    3.yml文件配置注册中心地址并开启info端点

    management:
      endpoints:
        web:
          exposure:
            include: health,info
    eureka:
      instance:
        hostname: localhost #当前实例的主机名字
      client:
        serviceUrl:
          defaultZone: http://peer1:1111/eureka/, http://peer2:1112/eureka/

    4.测试

    客户端 

    1.增加eurekapom依赖 用于服务发现

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

    2.application开启服务发现的注解

    @SpringBootApplication
    @EnableDiscoveryClient //开启服务发现
    public class SpringCloudConfigClientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringCloudConfigClientApplication.class, args);
        }
    
    }

    3.yml配置

    spring:
      application:
        name: config #对应{application}
      cloud:
        config:
          profile: dev #映射{profile}
          label: master #映射{label}
          #uri: http://127.0.0.1:7001 #config server地址
          username: liqiang #configserver身份认证用户名
          password: liqiang #configserver身份认证密码
          discovery:
            service-id: CONFIG-SERVER #configserver的服务名
            enabled: true #开启通过服务访问configserver的功能
    server:
      port: 7002
    eureka:
      instance:
        hostname: localhost #当前实例的主机名字
      client:
        serviceUrl:
          defaultZone: http://peer1:1111/eureka/, http://peer2:1112/eureka/

    将原来的url注释改为spring.cloud.discovery.service-id 指定configserver是那个服务  spring.coud.discovery.enabled=true 表示开启通过服务访问configserver

    快速响应与重试

    快速响应

    我们比较大的项目的时候刚开始启动会初始化一系列配置可能耗时5分钟。但是前面都没问题 当加载config的时候出现异常 前面的初始化就没有意义了。

    可以通过配置 如果config-server不通的时候能够马上抛出异常

    只需要通过配置

    spring.cloud.config.fail-fast=true

    重试

    当我们通过config-server加载失败的时候可以通过设定重试时间以及间隔,避免config-server出现网络占时不通而导致失败

    1.spring.cloud.config.fail-fast=true 增加了快速响应配置

    2.pom依赖

     <!--连接服务端重试的功能 依赖 前提 必须确保开启了fail-fast 默认6秒重试一次-->
            <dependency>
                <groupId>org.springframework.retry</groupId>
                <artifactId>spring-retry</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>

    3.我们再不启动config.server的时候启动client

    重试6此失败

    相关配置

    spring:
      cloud:
        config:
          retry:
            multiplier: 1.1 #默认间隔乘数  如果间隔是1000  下一次间隔是1100
            max-interval: 2000 #默认最大间隔数(毫秒)
            max-attempts: 6 #默认重试次数
            initial-interval: 1000 #默认间隔数 

    动态刷新配置 

    1.client pom增加依赖用于端点

    <!--开启端点  用于端点模块提供的 动态刷新配置 /refresh-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>

    2.client yml开启/refresh端点

    management:
      endpoints:
        web:
          exposure:
            include: refresh

    3.post请求访问http://127.0.0.1:7002/actuator/refresh 刷新配置

     ps:需要刷新配置的地方需要打上@RefreshScope注解,如:
    @Controller
    @RefreshScope
    public class ConfigInfoContorller {
        @Autowired
        private Environment environment;
        @RequestMapping("/getDataSorce")
        @ResponseBody
        public String getDataSource() {
            //读取配置 如果不存在返回undefined
            return environment.getProperty("data-source", "undefined");
        }
        @RequestMapping("/getEncryptionDataSource")
        @ResponseBody
        public String getEncryptionDataSource(){
            return environment.getProperty("dbdatasource", "undefined");
        }
    
    }
  • 相关阅读:
    【二次开发】shopxo商城
    经典的PHPer为什么被认为是草根?
    PowerDesigner生成Access数据库
    NET开发学习项目资源
    ASP.NET程序开发范例宝典
    Web.Config文件配置小记
    NET开发学习项目资源(2)
    VS 2010一步步开发windows服务(windows service)
    jquery.mobile手机网页简要
    Android置底一个View后运行报错
  • 原文地址:https://www.cnblogs.com/LQBlog/p/10244329.html
Copyright © 2020-2023  润新知