1. 程式人生 > 其它 >SpringCloud中整合Hystrix實現降級時通過FeignFallBack實現通配服務

SpringCloud中整合Hystrix實現降級時通過FeignFallBack實現通配服務

場景

SpringCloud中整合Hystrix實現服務降級(從例項入手):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/124948025

上面在進行降級配置的fallback時是通過如下方式配置

    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds
",value="2000") }) public String paymentInfo_TimeOut(Integer id) { //int age = 10/0; String result = paymentHystrixService.paymentInfo_TimeOut(id); return result; } public String paymentInfo_TimeOutHandler(Integer id) { return "執行緒池: "+Thread.currentThread().getName()+"
來自消費者88的提示:服務提供者繁忙或者執行報錯,請稍後再試,id: "+id+"\t"+"o(╥﹏╥)o"; }

但是這樣就需要在每個方法中重複添加註解並配置fallback方法。

有沒有可以通配的方式進行配置fallback。

注:

部落格:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取程式設計相關電子書、教程推送與免費下載。

實現

1、首先確保yml中如下配置已經開啟

feign:
  hystrix:
    enabled: true

2、然後新建一個類實現上面的Service介面,統一為接口裡面的方法進行異常處理

package com.badao.springclouddemo.service;

import org.springframework.stereotype.Component;


@Component
public class PaymentFallbackService implements PaymentHystrixService
{
    @Override
    public String paymentInfo_OK(Integer id)
    {
        return "-----PaymentFallbackService fall back-paymentInfo_OK ,o(╥﹏╥)o";
    }

    @Override
    public String paymentInfo_TimeOut(Integer id)
    {
        return "-----PaymentFallbackService fall back-paymentInfo_TimeOut ,o(╥﹏╥)o";
    }
}

3、給service介面中@FeignClinet註解中配置fallback屬性為上面的實現類

package com.badao.springclouddemo.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService
{
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id);


}

4、此時依次啟動Eureka Server 7001,以及服務提供者8001和服務消費者88

正常訪問服務確保沒問題

然後將8001關掉,模擬宕機的情況,此時服務消費者中呼叫對應的服務則會進入對應的實現中的返回。