1. 程式人生 > 其它 >2020-12-16 Hystrix(2)

2020-12-16 Hystrix(2)

技術標籤:Java# springcloud

11.3服務降級

是什麼?
  • 服務降級是當伺服器壓力劇增的情況下,根據當前業務情況及流量對一些服務和頁面有策略的降級,以此釋放伺服器資源以保證核心任務的正常執行。--------來源百度百科
怎麼用?
1. 在springcloud-api下的service層新建一個DeptClientServiceFallBackFactory類

   import com.buba.springcloud.pojo.Dept;
   import feign.hystrix.FallbackFactory;
   import org.springframework.
stereotype.Component; import java.util.List; //降級 @Component public class DeptClientServiceFallBackFactory implements FallbackFactory { @Override public DeptClientService create(Throwable throwable) { return new DeptClientService() { @Override public Dept queryById
(Long id) { return new Dept() .setDeptno(id) .setDname("這個id=>"+id+"沒有對應的資訊,客戶端掌握了降級的資訊,這個伺服器已經被關閉") .setDb_source("沒有資料"); } @Override public List<
Dept>
queryAll() { return null; } @Override public Boolean addDept(Dept dept) { return null; } }; } }
2. 給DeptClientService新增操作讓它可以去呼叫DeptClientServiceFallBackFactory類
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallBackFactory.class)
public interface DeptClientService {
    XXX
}
3. 在springcloud-consumer-dept-feign客戶端開啟降級
#開啟降級
feign:
  hystrix:
    enabled: true
4.啟動測試
  • 訪問http://localhost/consumer/dept/get/1
    可以看到:在這裡插入圖片描述
  • 訪問http://localhost/consumer/dept/get/6
    可以看到:在這裡插入圖片描述
  • 關閉springcloud-provider-dept-8001提供者,訪問http://localhost/consumer/dept/get/1
    可以看到:在這裡插入圖片描述

11.4小結

服務熔斷:
  • 服務端
  • 某個服務超時或者異常就會引起熔斷 類似保險絲
服務降級:
  • 客戶端
  • 從整體的網站負載考慮
  • 當某個服務熔斷或者關閉之後,服務將不再被呼叫.
  • 此時在客戶端我們可以準備一個FallBackFactory,返回一個預設的值(預設值),整體的服務水平下降了,好歹能用,比直接掛掉強