Spring-cloud 微服务架构搭建 02 - config-server 集成git动态刷新配置及安全管理

1. sping-cloud config简介

微服务的体系中,配置文件的统一管理是非常有必要的,我们需要替代人为手动维护配置文件的责任,因为在大型的微服务体系中我们需要维护的配置成百上千份,很容易发生配置漂移。此时,Spring-Cloud Config可以给我们提供配置的统一管理和分发,以及自动化刷新配置的需求。

2. sping-cloud config 服务特点

2.1. 分离性

Config配置中心支持将配置文件存入本地或者无缝衔接git管理的特性能够集中进行版本的控制和配置文件的管理;

2.2. 抽象性

我们在获取配置文件时,不需要自己进行配置文件读取操作,可以通过http请求配配置中心提供的服务进行配置文件读取,并且集成bus总线可以动态IDE刷新配置,并且刷新所有的服务实例无需重启机器;

2.3. 集中性

所有的配置文件信息集中存储在配置中心,有效的进行数据的版本统一管理。

2.4. 稳定性

作为spring旗下项目,与eureka、consul等紧密结合,可实现高可用部署,降低服务奔溃的风险,实现拉取一份配置文件本地缓存等特性来降低风险,保证了高可用和冗余。

3. Config-Server 服务端搭建

注:本文项目采用idea工具进行搭建

  • 使用idea自身的spring initializr进行项目的初始化,集成git使用的rabbitmq请自行搜索安装,如果是mac,请直接使用brew install rabbitmq即可
  • 初始化完成项目之后进行pom文件导入
<!-- config-server 启动引入 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!-- security 安全控制 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- eureka 服务注册 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 消息总线 配置动态配置中心 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  • 修改application.yml文件,添加如下配置:
spring:
  application:
    name: config-server
#  profiles:
#    active: native    #开启本地配置 默认为git
#  cloud:
#    config:
#      server:
#        native:
#          search-locations: classpath:config-repo
## git管理配置
  cloud:
    config:
      retry:
        initial-interval: 3000
        multiplier: 1.5
        max-interval: 20000
        max-attempts: 6
      server:
        git:
          uri: #个人git地址
          search-paths: '{application}'
          username: # 你个人的git账户
          password: # git密码
          default-label: master
  rabbitmq:
    host: localhost
    port: 5672
    username: guest #默认密码
    password: guest #默认密码
  # 安全认证 
  security:
    user:
      name: luhanlin
      password: ***
      
## 暴露所有监控端口 主要暴露动态刷新接口
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS
  • 修改bootstrap.yml文件,链接eureka-config,添加如下配置:
#服务注册中心配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/  #,http://xxxxx:8761/eureka/
      # 指定多少秒从注册中心获取一次实例服务列表 默认 30秒
      # 减少值可以解决服务注册慢问题,但一般不要设置太小
      registry-fetch-interval-seconds: 20
  instance:
    # 获取实例ip地址
    prefer-ip-address: true
    # 心跳包发送时间 默认 30秒
    lease-renewal-interval-in-seconds: 60
    # 最后一次心跳时间间隔以下值之后清楚实例列表中的值,不应该小于心跳检测时间 默认90秒
    lease-expiration-duration-in-seconds: 100
#    instance-id: config-server
  • 最后在Config服务启动实例上面添加一下注解:
@EnableDiscoveryClient  // 开启服务注册
@EnableConfigServer     // 开启配置中心服务端
@SpringBootApplication
public class ConfigServerApplication {

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

最后启动Eureka—server,在启动Config-Server就可以了,注意:rabbitmq服务需要启动,不然会报错。

4. Config-Client 端搭建

  • 此处我以Demo-Service项目为例。

  • 首先我们构建一个maven工程,初始化完成后进行pom引入(没有加入boot监控依赖):

<!-- Eureka客户端启动类 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Config客户端启动类 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>
<!-- 消息总线 配置动态配置中心 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  • 修改我们的配置文件Bootstrap.yml, 配置如下:
spring:
  application:
      name: demo
  # 配置中心服务的地址
  cloud:
    config:
      discovery:
        # 默认false,设为true表示使用注册中心中的config-server配置而不自己配置config-server的uri
        enabled: true
        service_id: config-server
      fail-fast: true
      name: demo
      profile:  dev # 要读取的配置文件profile属性
      # 使用git管理配置文件时指定
      label: master
      username: luhanlin
      password: ***
# 指定服务注册中心的位置。
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    hostname: localhost
    preferIpAddress: true
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS
  • 配置完后需要在Client启动类上加上一下注解:
@RefreshScope   # GIT动态刷新注解
@EnableDiscoveryClient # 服务发现

5. 动态刷新配置测试

// 此类进行配置文件的信息读取,**使用对象进行测试会更加准确**
@Data
public class CustomBean {
    private String id;
    private String name;
    private String version;
}

@Configuration  // 配置类,如不熟悉可以先行进行spring-b
public class BusinessConfig {

    @Bean
    @ConfigurationProperties(prefix="custom.bean")
    public CustomBean initCustomBean(){
        log.info(">>>>>>>>>>> CustomBean >>>>>>>>>>>>>>> 配置成功!!!");
        return new CustomBean();
    }
}

@RestController  // 对外api提供,最后返回配置中信息
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private CustomBean customBean;

    @GetMapping(value = "/hello")
    public ResultInfo hello(){
        return  ResultUtil.success(customBean.getVersion());
    }
}

// 配置文件(demo-dev.yml,位于个人仓库中)添加如下配置:
custom:
  bean:
    id: 100
    name: luhanlin
    version: 1.0.1
{
    "code": "I0000",
    "msg": "请求成功",
    "data": "1.0.1"
}
  • 修改配置仓库中的配置文件,并提交到push到远程git仓库
custom:
  bean:
    id: 100
    name: luhanlin
    version: 1.0.9
  • 这是再次访问http://localhost:8080/test/hello,发现返回信息没。使用POST请求访问http://localhost:7001/actuator/bus-refresh(老版使用fresh/refresh)进行属性的刷新,发现403无法访问请求,因为我在配置中添加了security配置需要进行安全认证,而新版的boot和cloud中需要Config-server中进行以下配置才行:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 高版本的丢弃了 
     * 
     * security: 
     *   basic: 
     *    enabled: true 
     * 
     * 配置,应该使用以下方式开启
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Configure HttpSecurity as needed (e.g. enable http basic).
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
        http.csrf().disable();
        //注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
        // 如果是form方式,不能使用url格式登录
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}
  • 完成后调用http://localhost:7001/actuator/bus-refresh,接口请求完成后可以看到控制台进行了配置刷新,再次访问http://localhost:8080/test/hello接口返回:
{
    "code": "I0000",
    "msg": "请求成功",
    "data": "1.0.9"
}
  • 配置成功

6. config-server配置RSA加密

  • 由于我们配置文件时很多需要加密的信息不宜暴露给外界,需要进行各种加密操作,其中spring-cloud提供了对称加密和RSA非对称加密的形式,此处我们使用RSA加密的方式,通过Config暴露的entrypt接口进行加密,我们只需要在配置文件中使用{cipher},如:“{cipher}shdshdswwhxxxxxxxx66x65xsdsdsd”,其中在yml配置文件中一定要使用双引号包含起来,不然会出错,详细的RSA配置大家可以自行搜索博客进行配置。

本文github代码地址
spring-cloud 基础模块搭建 – 欢迎指正

猜你喜欢

转载自blog.csdn.net/allen_lu_hh/article/details/83107051