【修真院JAVA小課堂】如何使用分散式配置中心?
大家好,我是IT修真院深圳分院第十一期學員,一枚正直純潔善良的JAVA程式設計師。
今天給大家分享一下,修真院官網JAVA任務十的一個知識點:如何使用分散式配置中心?
1 背景介紹 1.1 SpringCloud簡介 springCloud是基於SpringBoot的一整套實現微服務的框架。他提供了微服務開發所需的配置管理、服務發現、斷路器、智慧路由、微代理、控制匯流排、全域性鎖、決策競選、分散式會話和叢集狀態管理等元件。 SpringBoot旨在簡化建立產品級的 Spring 應用和服務,簡化了配置檔案,使用嵌入式web伺服器,含有諸多開箱即用微服務功能 2 知識剖析 2.1 什麼是分散式配置中心? 在微服務架構的系統中,使用一個統一的微服務進行配置檔案的載入,由這個微服務向其他服務提供配置檔案,這個微服務就是配置中心。 2.2 什麼是SpringCloudBus? Spring cloud bus即SpringCloud框架的訊息匯流排。其本質是利用了MQ的廣播機制在分散式的系統中傳播訊息,目前常用的有Kafka和RabbitMQ。利用bus的機制可以做很多的事情,其中配置中心客戶端重新整理就是典型的應用場景之一。 2.3 使用SpringCloudBus實現自動更新配置的步驟有哪些? 1) 設定配置中心,config-server,從git獲取配置資訊; 2) 在service中呼叫config-server中的相關配置; 3) 在service中匯入SpringCloudBus相關依賴,配置RabbitMq; 4) 在需要重新整理配置的Controller上新增@RefreshScope註解 5) 在GitHub上配置WebHook,設定更新properties檔案後向config-server傳送post請求。
3 常見問題 如何使用SpringCloudBus實現自動更新配置4 解決方案 1、見編碼實戰5 編碼實戰
config-server的yml配置
server: port: 8091 eureka: instance: prefer-ip-address: true client: registerWithEureka: true fetchRegistry: true serviceUrl: defaultZone: http://localhost:8090/eureka/ spring: application: name: config-server cloud: config: server: git: uri: https://github.com/ search-paths: respo label: master bus: enabled: true trace: enabled: true rabbitmq: host: localhost port: 5672 username: guest password: guest management: endpoints: web: exposure: include: bus-refresh
service的yml配置
server: port: 8081 spring: application: name: service-hi cloud: bus: enabled: true trace: enabled: true config: lable: master profile: dev uri: http://193.112.45.68:8091/ rabbitmq: host: 193.112.45.68 port: 5672 username: guest password: guest eureka: client: registerWithEureka: true fetchRegistry: true serviceUrl: defaultZone: http://193.112.45.68:8090/eureka/ instance: hostname: localhost
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Hello {
@Value("${type}")
private String type;
@RequestMapping(value = "/hello")
public String te() {
return type ;
}
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class Hi {
@Value("${type}")
private String type;
@RequestMapping(value = "/hi")
public String te() {
return type ;
}
}
6 擴充套件思考
7 參考文獻 CSDN、百度百科8 更多討論 8.1 @RefreshScope的作用是什麼? 該註解用來標註需要重新整理的類,只有加上了這個註解,才會對這個類所引用的配置進行重新整理。8.2 服務註冊中心、服務配置中心和具體的服務模組是不是必須要放在同一個伺服器上? 不需要,只需要在yml檔案中指定地、開放相關的埠即可。8.3 GitHub的webHook功能如何配置? 1) 找到連線的庫,開啟Setting頁面; 2) 選擇webHook,新增webhook; 3) 填寫傳送POST請求的地址及何時傳送POST請求
技能樹.IT修真院
“我們相信人人都可以成為一個工程師,現在開始,找個師兄,帶你入門,掌控自己學習的節奏,學習的路上不再迷茫”。
這裡是技能樹.IT修真院,成千上萬的師兄在這裡找到了自己的學習路線,學習透明化,成長可見化,師兄1對1免費指導。
快來與我一起學習吧~http://www.jnshu.com/login/1/24864700
騰訊視訊:https://v.qq.com/x/page/c0719197opo.html