spring-cloud-gateway降級的實現(xiàn)
前言
本文主要研究一下 spring cloud gateway 如何集成 hystrix。
當下游接口負載很大,或者接口不通等其他原因?qū)е鲁瑫r,如果接口不熔斷的話將會影響到下游接口得不到喘息,網(wǎng)關(guān)也會因為超時連接一直掛起,很可能因為一個子系統(tǒng)的問題導(dǎo)致整個系統(tǒng)的雪崩。所以我們的網(wǎng)關(guān)需要設(shè)計熔斷,當因為熔斷器打開時,網(wǎng)關(guān)將返回一個降級的應(yīng)答。
Maven 配置
添加 hystrix 依賴
pom.xml
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
項目實戰(zhàn)
在 provider1 服務(wù)中添加一個方法,延時 2 秒返回響應(yīng)。
@GetMapping('/timeout') public String timeout() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println('休眠了2秒'); return 'timeout test'; }
修改網(wǎng)關(guān)配置文件
server: port: 2000spring: application: name: idc-gateway2 redis: host: localhost port: 6379 timeout: 6000ms # 連接超時時長(毫秒) jedis: pool: max-active: 1000 # 連接池最大連接數(shù)(使用負值表示沒有限制) max-wait: -1ms # 連接池最大阻塞等待時間(使用負值表示沒有限制) max-idle: 10 # 連接池中的最大空閑連接 min-idle: 5 # 連接池中的最小空閑連接 cloud: consul: host: localhost port: 8500 gateway: discovery: locator: enabled: true # gateway可以通過開啟以下配置來打開根據(jù)服務(wù)的serviceId來匹配路由,默認是大寫 routes: - id: provider1 uri: lb://idc-provider1 predicates: - Path=/p1/** filters: - StripPrefix=1 - name: Hystrix args:name: defaultfallbackUri: forward:/defaultfallback # 只有該id下的服務(wù)會降級 - id: provider2 uri: lb://idc-provider2 predicates: - Path=/p2/** filters: - StripPrefix=1# hystrix 信號量隔離,1.5秒后自動超時hystrix: command: default: execution: isolation: strategy: SEMAPHORE thread: timeoutInMilliseconds: 1500
網(wǎng)關(guān)添加降級處理類
@RestControllerpublic class FallbackController {@RequestMapping('/defaultfallback')public Map<String,Object> defaultfallback(){System.out.println('降級操作...');Map<String,Object> map = new HashMap<>();map.put('code',200);map.put('msg','服務(wù)超時降級');map.put('data',null);return map;}}
降級測試
超時服務(wù)降級
curl http://localhost:2000/p1/timeout
返回
{'msg':'服務(wù)超時降級','code':200,'data':null}
其他異常
spring-cloud-gateway 調(diào)用下游服務(wù)返回的異常,網(wǎng)關(guān)不做任何處理,會直接返回。大家想一下為什么在網(wǎng)關(guān)不去處理下游異常呢? 因為很多時候下游的異常是包含有效信息的(異常信息千千萬),如果在網(wǎng)關(guān)處做了統(tǒng)一返回,就失去了返回異常的意義。
spring-cloud-starter-netflix-hystrix 內(nèi)置的 Hystrix 過濾器是HystrixGatewayFilterFactory。 感興趣的小伙伴可以自行閱讀相關(guān)源碼。
到此這篇關(guān)于spring-cloud-gateway降級的實現(xiàn)的文章就介紹到這了,更多相關(guān)spring-cloud-gateway降級 內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python2.6版本pip安裝步驟解析2. python公司內(nèi)項目對接釘釘審批流程的實現(xiàn)3. python中Ansible模塊的Playbook的具體使用4. Python自動化之定位方法大殺器xpath5. Python本地及虛擬解釋器配置過程解析6. Python 利用flask搭建一個共享服務(wù)器的步驟7. 基于python實現(xiàn)matlab filter函數(shù)過程詳解8. Python中Anaconda3 安裝gdal庫的方法9. python自動化測試三部曲之request+django實現(xiàn)接口測試10. Python importlib模塊重載使用方法詳解
