【微服務】之三:從零開始,輕松搞定SpringCloud微服務-配置中心


在整個微服務體系中,除了注冊中心具有非常重要的意義之外,還有一個注冊中心。注冊中心作為管理在整個項目群的配置文件及動態參數的重要載體服務。Spring Cloud體系的子項目中,Spring Cloud Config子項目就是該注冊中心。在整個分布式框架系統中,充當重要角色。

官方解釋

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer's own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.

本系列博文目錄

【微服務】從零開始,輕松搞定SpringCloud微服務目錄

說明:本系列源碼持續更新,開始本篇之前先了解前面幾篇文章。

開始起飛

基本思路:本文采用Git倉庫作為配置文件的存放地址,通過創建一個配置中心服務器啟動服務,然后再通過創建一個配置中心的客戶端進行測試是否正常運轉。

創建配置中心倉庫

在原有的父類項目下創建一個普通的子項目,可以刪除無關的文件,只留下空白項目。然后再創建一個測試的配置文件。
image.png

配置文件中加入測試數據

#隨意設置的一個參數
myblog:
  name: 千萬之路剛開始-author-hyh
  url: http://www.hanyahong.com
  location: BeiJing

創建配置中心服務端

創建子項目

image.png

POM文件配置

在pom.xml文件中做一下配置


<dependencies>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-config-server</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-eureka</artifactId>
   </dependency>
</dependencies>
<build>
   <plugins>
       <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
       </plugin>
   </plugins>
</build>

配置項目resource配置文件

:整個博客是對各個子項目整合,因此加入了服務注冊中心的相關配置

在resources文件夾下創建application.yml文件。並加入以下配置:

#服務端口
server:
  port: 8082

#服務注冊中心配置
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8081/eureka/

#spring設置
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/hanyahong/spring-cloud-microservice.git
          searchPaths: cloud-hyh-config-repo


創建主方法類

在創建完包以后,創建主方法。


@EnableDiscoveryClient
@SpringBootApplication
@EnableConfigServer
public class ConfigApplication {

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

至此,服務端配置完畢,啟動服務器即可,等待客戶端驗證。

創建客戶端

創建一個配置客戶端,對剛剛的服務進行測試。
@EnableDiscoveryClient: 服務發現客戶端注解,用於被發現。
@EnableConfigServer: 開啟配置中心服務器配置。

創建客戶端子項目

image.png

配置pom文件

在子項目pom.xml中加入一下依賴及插件。

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

創建配置文件

在子項目中resources文件夾下,創建bootstrap.yml文件。加入一下配置。

spring:
  application:
    #本項目名稱
    name: config-client
  cloud:
    config:
      #配置中心服務器地址配置
      uri: http://localhost:8082/
      profile: default
      label: master
      retry:
        # 配置重試次數,默認為6
        max-attempts: 6
        # 間隔乘數 默認1.1
        multiplier: 1.1
        # 初始重試間隔時間,默認1000ms
        initial-interval: 1000
        # 最大間隔時間,默認2000ms
        max-interval: 2000

server:
  port: 8091
#服務發現配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/

創建程序入口

創建默認包以后創建ConfgClientApplication.java 文件。

/** 
 * @Description :配置中心啟動類
 * @Author hanyahong
 * @Date 2017/12/6- 14:06
 */


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

創建測試API

創建一個測試API文件,TestApi.java。

/**
 * @Description :配置中心-客戶端展示API
 * @Author hanyahong
 * @Date 2017/12/6- 16:39
 */
@RefreshScope
@RestController

public class TestApi {

    @Value("${myblog.name}")
    private String name;
    @Value("${myblog.url}")
    private String url;
    @Value("${myblog.location}")
    private String location;
    @RequestMapping("/blog-info")
    public String getBlogInfo() {
        return "從Github倉庫中獲取得到我博客信息:【"+location+","+","+url+","+name+"】";
    }
}

@RefreshScope:開啟刷新

至此,配置中心測試的客戶端基本完畢。
對於子項目來說有三個子項目:
cloud-hyh-config 端口號:8082
cloud-hyh-config-client 端口號:8091
cloud-hyh-config-repo 純存儲使用,該文檔下面的配置文件一定要上傳到倉庫后,才可以遠程獲取。

啟動項目並測試

對服務注冊中心(上篇有寫)、服務配置中心、服務客戶端分別進行啟動。
可以通過注冊中心查看是否都已經被納入管理。
image.png

測試一: 注冊中心測試
首先通過訪問配置中心服務器的地址可以進行測試是否獲取成功。
訪問 http://localhost:8082/config-client.yml 對倉庫中資源文件 測試是否返回結果。
另外也可以通過 http://localhost:8082/config-client/master 進行訪問。瀏覽器顯示返回結果:

"name":"config-client","profiles":["master"],"label":null,"version":"7169e90f628c85d582f3f9d5fceda36696ebd751","state":null,"propertySources":[{"name":"https://github.com/hanyahong/spring-cloud-microservice.git/cloud-hyh-config-repo/config-client.yml","source":{"myblog.name":"千萬之路剛開始-author-hyh","myblog.url":"http://www.hanyahong.com","myblog.location":"BeiJing","config-client.name":"test"}}]}

測試二: 客戶端訪問API測試
通過客戶端訪問API http://localhost:8091/blog-info 顯示結果:
從Github倉庫中獲取得到我博客信息:【BeiJing-Customs,,http://www.hanyahong.com,千萬之路剛開始-author-hyh】
測試成功!

測試三: 動態更新參數測試
配置中心一個重要的功能就是你無須重啟去生效一些參數配置,系統可以通過訪問/refresh 進行動態刷新,將參數生效。

  1. 修改配置文件信息,上傳git倉庫。
  2. 使用PostMan 或其他工具進行一次POST請求 API:http://localhost:8091/refresh (一定要看清楚,POST請求,瀏覽器直接訪問無效,會報Request method 'GET' not supported 錯誤)。
  3. 再一次訪問 http://localhost:8091/blog-info ,可以看到已在未重啟的情況下,配置動態更新。

后續說明

因配置中心涉及很多數據的更新,不可能每次通過這種方式去動態更新,后續會有專門消息總線模塊的講解,將通過消息總線的機制去進行配置的傳輸。

源碼地址

GitHub:https://github.com/hanyahong/spring-cloud-microservice


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM