Feign+Hystrix 實現服務熔斷


1.首先在服務消費端引入Hystrix依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

2.啟用Feign的Hystrix

feign:
   hystrix:
      enabled: true

3.修改feign接口,指定熔斷處理類

@FeignClient(value = "service-helloworld",fallback = HelloApiFallback.class)
public interface HelloApi {

    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    public String sayHello(@RequestParam("name")String name);
}

4.編寫熔斷實現類:HelloApiFallback

@Component
public class HelloApiFallback implements HelloApi{
    @Override
    public String sayHello(String name) {
        return "服務異常,啟動熔斷,HelloWorld";
    }
}

5.測試

分別啟動注冊中心,服務提供者,服務消費者,

在瀏覽器輸入http://localhost:8120/hello?name=老王

可以看到會顯示:

hello world ,老王

關掉服務提供者,再次訪問上面地址,會顯示:

服務異常,啟動熔斷,HelloWorld

表示,熔斷已經生效。

再次啟動服務提供者,訪問http://localhost:8120/hello?name=老王

會顯示:hello world ,老王

表示服務恢復后,熔斷關閉。

6.關掉部分接口的熔斷處理。

配置文件啟動Hystrix后,Feign就會使用斷路器包裹Feign客戶端的所有方法。這樣雖然方便,但是很多場景下並不需要該功能。

如果上面的api,去掉fallback 方法會報錯。

錯誤如下:

There was an unexpected error (type=Internal Server Error, status=500).
HelloApi#sayHello(String) timed-out and no fallback available.

需要加下Hystrix配置,代碼如下:

@Configuration
public class FeignDisableHystrixConfiguration {
    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder();
    }
}

 

再在對應不需要實現熔斷的地方指定該配置類

@FeignClient(value = "service-helloworld",configuration = FeignDisableHystrixConfiguration.class)
public interface HelloApi {

    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    public String sayHello(@RequestParam("name")String name);
}

 

源碼地址:

 源碼地址:https://gitee.com/zhuyuehua/springcloud_helloWorld

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM