spring cloud Hystrix
spring cloud Hystrix
文章目錄
- spring cloud Hystrix
- pom.xml依賴
- 開啟短路器功能
- 服務降級
- @HystrixCommand的fallbackMethod
- 配置默認的服務降級方法
- 使用openfeign中的hystrix
- 配置application.yml
- @FeignClient的fallback屬性配置服務降級的類
- 服務熔斷
- @HystrixCommand配置斷路器
- 使用案例
- Hystrix的儀表盤
- pom.xml依賴
- 啟動類
- 訪問接口
- 監控展示
- 報錯Unable to connect to Command Metric Stream.
pom.xml依賴
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix --> <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId><version>2.2.2.RELEASE</version> </dependency>開啟短路器功能
要使用Hystrix服務這些功能的,需要在主啟動類添加@EnableCircuitBreaker注解
@SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker public class PaymentApplication8003 {public static void main(String[] args) {SpringApplication.run(PaymentApplication8003.class,args);}}服務降級
服務降級,當服務器壓力劇增的情況下,根據當前業務情況及流量對一些服務和頁面有策略的降級,以此釋放服務器資源以保證核心任務的正常運行。
處理超時,處理異常等都會觸發服務降級,當某個微服務發生一些網絡擁擠現象時,微服務模塊未能及時返回數據時,我們就可以通過服務降級對超時等現象進行處理(如返回一些提示信息,通知用戶系統繁忙稍后在試),這樣就可以及時釋放掉資源,以免發生過長的等待,導致資源的長時間占用。
@HystrixCommand的fallbackMethod
@HystrixCommand中的fallbackMethod指定服務降級方法
配置服務降級@HystrixCommand中的fallbackMethod屬性進行配置,commandProperties屬性用于設置command的配置屬性。
@HystrixCommand(fallbackMethod = "createFallback",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")}) public int create(Payment payment) {return paymentDao.create(payment); }public int createFallback(Payment payment){System.out.println("創建出錯");return Integer.MAX_VALUE; }配置默認的服務降級方法
通過@DefaultProperties可以配置一些默認的配置,如:defaultFallback,commandProperties等。
下面的代碼中的PaymentServiceImpl配置了一個defaultFallback,當一個方法上面的@HystrixCommand沒有配置相應的屬性時,默認使用@DefaultProperties聲明的屬性。所以下面的代碼中create方法使用的降級方法是createFallback,而getPaymentById則使用默認的global_fallbackfunction
注意點:服務降級的方法應該跟源配置方法一致,如:int create(Payment payment)那么它的服務降級方法返回值必須為int,傳入參數必須為Payment類型。
@Service @DefaultProperties(defaultFallback = "global_fallbackfunction") public class PaymentServiceImpl implements PaymentService {@Resourceprivate PaymentDao paymentDao;@HystrixCommand(fallbackMethod = "createFallback",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")})public int create(Payment payment) {return paymentDao.create(payment);}@HystrixCommandpublic Payment getPaymentById(int id) {return paymentDao.getPaymentById(id);}//---------------------------------------------------------------public int createFallback(Payment payment){System.out.println("創建出錯");return Integer.MAX_VALUE;}public Payment global_fallbackfunction(int id){System.out.println("全局默認fallback方法");return null;} }使用openfeign中的hystrix
openfeign中帶有hystrix,使用openfeign也可以配置服務降級功能。
配置application.yml
通過feign.hystrix.enabled開啟hystrix的功能,默認是關閉的。
feign:hystrix:enabled: true@FeignClient的fallback屬性配置服務降級的類
用過openfeign的應該都知道使用@FeignClient注解,用于定義要代理的服務端的接口,打上這個注解后,feign就會掃描這個注解生成代理類,然后通過這個代理類就能直接調用服務端的暴露的接口了。
1.服務端暴露的接口
這個服務端已經將服務注冊到Eureka上,并且這個服務名稱為CLOUD-PAYMENT-SERVICE 。
@RestController @Slf4j public class PaymentController {@Resourceprivate PaymentServiceImpl paymentServiceImpl;@Value("${server.port}")private String port;@GetMapping("/payment/get/{id}")public ResponseMessage getPaymentById(@PathVariable("id") int id){Payment payment = paymentServiceImpl.getPaymentById(id);return ResultFactory.buidResult(200,"成功"+port,payment);} }2.消費端指定Feign要代理的接口
這里是消費端的代碼,通過@FeignClient指定要代理服務名稱,要代理的接口。然后openFeign將會生成代理對象。
//代理CLOUD-PAYMENT-SERVICE服務的接口,并指定服務降級的類 @Component @FeignClient(value = "CLOUD-PAYMENT-SERVICE",fallback = PaymentFallback.class) public interface PaymentOpenfeginService {//服務端的接口@GetMapping("/payment/get/{id}")public ResponseMessage getPaymentById(@PathVariable("id") int id); }3.使用代理對象
@RestController @Slf4j public class OrderController {//注入接口的代理對象@Resourceprivate PaymentOpenfeginService paymentOpenfeginService;@GetMapping("/comsumer/payment/get/{id}")public ResponseMessage getPaymentById(@PathVariable("id") int id){//直接通過代理對象即可調用服務端接口return paymentOpenfeginService.getPaymentById(id);}}4.編寫服務降級類
上面@FeignClient注解通過屬性fallback指定了要降級的類,當openFeign的代理類的代理方法需要進行服務降級時,就會通過fallback中指定的類中對應的方法進行服務降級方法的調用。
@Component public class PaymentFallback implements PaymentOpenfeginService {//當getPaymentById需要服務降級時,將調用其對應我服務降級方法public ResponseMessage getPaymentById(int id) {System.out.println("服務降級");return null;} }服務熔斷
服務熔斷,一種源于電子工程的斷路器的概念。
微服務往往過個服務中間進行調用,而多個服務之間進行調用就會形成一個調用鏈。當下游服務因訪問壓力過大而響應變慢或失敗,上游服務為了保護系統整體的可用性,可以暫時切斷對下游服務的調用。
說穿了就是當某個微服務發生網絡擁擠現象,而觸發多次服務降級措施時,我們就可以對改服務的調用進行切斷(服務恢復前調用不再調用),這就像電路的斷路器一樣,咔的一下斷閘。等到發生故障的微服務能再次被調用的時候,再恢復調用。
@HystrixCommand配置斷路器
服務熔斷還是需要使用到@HystrixCommand注解。
關于@HystrixProperty的屬性去哪找,我們可以通過HystrixPropertiesManager這個類去獲取屬性,這個類就是用于獲取配置屬性的。
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;HystrixCommandProperties的默認值可以從這個類找到
import org.springframework.cloud.netflix.hystrix.HystrixProperties;使用案例
下面的代碼配置了一個斷路器,有一些特點:
- 他的降級方法是fallbackfunction
- 超時時間窗口為10秒
- 統計近10請求,失敗率超過60%及打開斷路器
還有一點要注意的是,斷路器是可以自動關閉的,如果斷路器為開啟狀態(服務熔斷了),當有一些請求到達這里時,斷路器嘗試開啟,就是半開,如果服務恢復,
@GetMapping("/payment/get/{id}")@HystrixCommand(fallbackMethod = "fallbackfunction",commandProperties = {@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),//開啟斷路器@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),//請求次數@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000"),//時間窗口@HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "60")})//失敗率閾值 public ResponseMessage getPaymentById(@PathVariable("id") int id){Payment payment = paymentServiceImpl.getPaymentById(id);return ResultFactory.buidResult(200,"成功"+port,payment); }public ResponseMessage fallbackfunction(){return ResultFactory.buildFailResult("失敗"); }Hystrix的儀表盤
pom.xml依賴
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix-dashboard --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId> </dependency>啟動類
@SpringBootApplication @EnableHystrixDashboard public class HystrixDashboardRun {public static void main(String[] args) {SpringApplication.run(HystrixDashboardRun.class,args);} }訪問接口
訪問接口跟你配置的服務端口有關,我這里配置的是9981
http://localhost:9981/hystrix然后輸入你要監控的服務端口即可使用,注意被監控的服務必須配置好了spring-boot-starter-actuator,要不就無法進行監控。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId> </dependency>監控展示
報錯Unable to connect to Command Metric Stream.
請在被監控測配置一個bean,以解決無法獲得監控流服務。
@Bean public ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}總結
以上是生活随笔為你收集整理的spring cloud Hystrix的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 红茜草的功效与作用、禁忌和食用方法
- 下一篇: 艾米果的功效与作用、禁忌和食用方法