show me the code and talk to me,做的出來更要說的明白
本文源碼,請點擊 learnSpringCloud
我是布爾bl,你的支持是我分享的動力!
一、引入
上回 基於 Spring Cloud 的微服務架構實踐指南(上) 介紹了 Spring Cloud
的常見組件,我們接着繼續進入 Spring Cloud
的實戰教程,擼起袖子,真槍實彈幹一場。在實戰演練中感受一下 Spring Cloud
的魅力所在。在教程中,我會繼續將 Spring Cloud
常見組件進行整合。整個過程就像搭積木一樣,一點一點地完成一個微服務工程的搭建。實戰演練是比較繁瑣的,但是隻要我們真正地去做了,就會收穫很多。
二、hystrix
組件( 服務熔斷 )
hystrix
組件主要作用是服務熔斷以及服務降級。可以在我們犯錯的時候,再給我們一次機會。他就像家裏的短路開關,對程序起到保護作用。另一方面其實覺得和 java
的異常機制相似。當項目發生未知異常, hystrix
組件就會挺身而出,作爲項目的貼身保鏢,爲項目保駕護航。當然,你認我的代碼沒有bug
,那麼你可以把他放在一邊。另外hystrix
組件提供了一個監控功能,但是沒有圖形化,我們可以使用相關依賴引入圖像化界面。
2.1 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
文件了。
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
組件主要是提供路由與過濾器功能。一般作爲項目的大門守衛,對所有進入項目的接口進行檢查。就像地鐵的安保人員一樣,會對每一個進入地鐵的人員進行一一 的檢查,發現不符合地鐵管理條例的人員不予進入。這就是過濾功能,同時當你迷路的時候,你可以詢問安保人,他會爲你指導方向,這就是路由功能。
加入服務網關的項目架構
3.1 pom
文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
3.2 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
組件主要是利用 git
作爲配置服務站,實現文件統一管理。當配置文件更新的時候,我們就可以拉去最新的文件。
五、github
https://github.com/buerbl/learnSpringCloud