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();
    }
}
{
    "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 基礎模塊搭建 -- 歡迎指正

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容