5.Hystrix-服務降級

所謂降級,就是當某個服務出現異常以後,服務器將再也不被調用,此時服務端能夠本身準備一個本地的fallback回調,返回一個缺省值。
這樣作,雖然服務水平降低,但好歹可用,比直接掛掉要強,固然這也要看適合的業務場景。java

啓動類:web

package com.wangfajun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; //@SpringBootApplication //@EnableDiscoveryClient //@EnableCircuitBreaker //開啓斷路器 @SpringCloudApplication public class FajunClientTestApplication { public static void main(String[] args) { SpringApplication.run(FajunClientTestApplication.class, args); } }

服務端代碼demo(客戶端請求服務端serverMethod方法時,若是服務端宕機或是serverMethod拋出異常,則將調用defaultFallback方法):spring

package com.odao.client.controller; import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.web.bind.annotation.*; @RestController @DefaultProperties(defaultFallback = "defaultFallback") public class FeignClientTestController { @HystrixCommand @GetMapping(value = "serverMethod") public String serverMethod() {
    /*throw new RuntimeException("異常了");*/
    return null; 
  }

  public String defaultFallback() {
    return "太擁擠了";
  }

pom:服務器

<!--hystrix-->
 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
相關文章
相關標籤/搜索