javascript
(七)SpringBoot+SpringCloud —— 集成断路器
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
斷路器簡(jiǎn)介
在一個(gè)項(xiàng)目中,系統(tǒng)可能被拆分成多個(gè)服務(wù),例如用戶、訂單和庫(kù)存等。
這里存在這服務(wù)調(diào)用服務(wù)的情況,例如,客戶端調(diào)用訂單服務(wù),訂單服務(wù)又調(diào)用庫(kù)存服務(wù)。
此時(shí)若庫(kù)存服務(wù)響應(yīng)緩慢,會(huì)直接導(dǎo)致訂單服務(wù)的線程被掛起,以等待庫(kù)存申請(qǐng)服務(wù)的響應(yīng),在漫長(zhǎng)的等待之后用戶會(huì)因?yàn)檎?qǐng)求庫(kù)存失敗而得到創(chuàng)建訂單失敗的結(jié)果。
如果在高并發(fā)下,因這些掛起的線程在等待庫(kù)存服務(wù)的響應(yīng)而未能獲得釋放,會(huì)似的后續(xù)到來的請(qǐng)求被阻塞,最終導(dǎo)致訂單服務(wù)也不可用。
在分布式架構(gòu)中,斷路器模式的作用也是類似的,當(dāng)某個(gè)服務(wù)單元發(fā)生故障之后,通過斷路器的故障監(jiān)控,向調(diào)用方返回一個(gè)錯(cuò)誤響應(yīng),而不是漫長(zhǎng)的等待。
快速入門
首先,添加斷路器hystrix的依賴。
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-hystrix</artifactId></dependency>接著在工程的主類,添加注解@EnableCircuitBreaker:
package cn.net.bysoft.owl.bookstore.web.console;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate;@SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class OwlBookstoreWebConsoleApplication {@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(OwlBookstoreWebConsoleApplication.class, args);} }接著,就可以使用斷路器了,可以添加@HystrixCommand注解,對(duì)調(diào)用服務(wù)的方法進(jìn)行修飾:
@HystrixCommand(fallbackMethod = "findByIdFallback")public User findById(Long id) {UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://SERVICE-USER/users/{id}").build().expand(id).encode();URI uri = uriComponents.toUri();return restTemplate.getForObject(uri, User.class);}public User findByIdFallback(Long id) {return null;}fallbackMethod是服務(wù)發(fā)生異常時(shí),回調(diào)的降級(jí)處理函數(shù),該函數(shù)的參數(shù)和返回值要與調(diào)用函數(shù)一致。
斷路器的默認(rèn)超時(shí)時(shí)間為2000毫秒。當(dāng)被斷路器修飾的函數(shù)執(zhí)行超過這個(gè)值,將觸發(fā)斷路器的服務(wù)降級(jí),該參數(shù)是可以設(shè)置的。
斷路器配置
全局配置屬性:hystrix.[attr].default.
實(shí)例配置屬性:hystrix.[attr].[key].
execution配置
Github
https://github.com/XuePeng87/owl-bookstore
轉(zhuǎn)載于:https://my.oschina.net/u/2450666/blog/1499040
總結(jié)
以上是生活随笔為你收集整理的(七)SpringBoot+SpringCloud —— 集成断路器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python-数据结构-大学生-航空订票
- 下一篇: Spring MVC面试题