
show me the code and talk to me,做的出來更要說的明白
本文源碼,請點選
learnSpringCloud 我是布爾bl,你的支援是我分享的動力!
一、引入
上回
基于 Spring Cloud 的微服務架構實踐指南(上)介紹了
Spring Cloud
的常見元件,我們接着繼續進入
Spring Cloud
的實戰教程,撸起袖子,真槍實彈幹一場。在實戰演練中感受一下
Spring Cloud
的魅力所在。在教程中,我會繼續将
Spring Cloud
常見元件進行整合。整個過程就像搭積木一樣,一點一點地完成一個微服務工程的搭建。實戰演練是比較繁瑣的,但是隻要我們真正地去做了,就會收獲很多。
二、 hystrix
元件( 服務熔斷 )
hystrix
hystrix
元件主要作用是服務熔斷以及服務降級。可以在我們犯錯的時候,再給我們一次機會。他就像家裡的短路開關,對程式起到保護作用。另一方面其實覺得和
java
的異常機制相似。當項目發生未知異常,
hystrix
元件就會挺身而出,作為項目的貼身保镖,為項目保駕護航。當然,你認我的代碼沒有
bug
,那麼你可以把他放在一邊。另外
hystrix
元件提供了一個監控功能,但是沒有圖形化,我們可以使用相關依賴引入圖像化界面。
2.1 pom
檔案
pom
我們引入
hystrix
的依賴。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
2.2 yml
檔案
yml
引入必要子產品後,我們就要去配置
yml
檔案了。
server:
port: 8010 # 端口
spring:
application:
name: microservicloud-hystrix # 給子產品起一個名字
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka # 注冊中心位址
instance:
instance-id: microservicloud-hystrix-8010
prefer-ip-address: true
2.3 啟動類
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //啟動斷路器
@EnableDiscoveryClient // 啟動圖像化監控
@RestController
public class AppApllcation8005 {
public static void main( String[] args ) {
SpringApplication.run(AppApllcation8005.class, args);
}
@GetMapping("/hellohystrix")
@HystrixCommand(fallbackMethod = "fallback") // 發生異常執行響應方法
public String hystrix() {
int i = 1 / 0;
return "hellohystrix";
}
public String fallback() {
return "出錯了";
}
}
2.4 啟動效果
啟動注冊中以及
hystrix
元件項目。
通路 http://localhost:8010/hellohystrix 接口:
通路 http://localhost:8010/hystrix 接口:
三、 zuul
元件(服務網關)
zuul
zuul
元件主要是提供路由與過濾器功能。一般作為項目的大門守衛,對所有進入項目的接口進行檢查。就像地鐵的安保人員一樣,會對每一個進入地鐵的人員進行一一 的檢查,發現不符合地鐵管理條例的人員不予進入。這就是過濾功能,同時當你迷路的時候,你可以詢問安保人,他會為你指導方向,這就是路由功能。
加入服務網關的項目架構
3.1 pom
檔案
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
3.2 yml
檔案
yml
server:
port: 8005 # 端口
spring:
application:
name: microservicloud-zuul-gateway # 項目名稱
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka # 注冊中心
3.3 啟動類
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy // 啟動zuul 元件
public class AppApllcation8005 {
public static void main( String[] args ) {
SpringApplication.run(AppApllcation8005.class, args);
}
}
3.4 啟動效果
通路 http://localhost:8005/microservicloud-dept/list 接口:
可以看到我們通過網關位址就通路到了服務端接口。這就是服務網關的路由功能。
四、 config
元件(配置中心)
config
當項目越來越多,伴随的配置檔案也越來越多。我們是否可以将這次雜亂無章的檔案統一進行管理呢,答案是可以的。這就是
config
元件的作用。
config
元件主要是利用
git
作為配置服務站,實作檔案統一管理。當配置檔案更新的時候,我們就可以拉去最新的檔案。
五、github
https://github.com/buerbl/learnSpringCloud
六、關注微信公衆号,随時移動端閱讀
http://weixin.qq.com/r/QS64oJ-E1sKprdvD93tT (二維碼自動識别)