1、spring cloud---feign+Hystrix熔斷器實現(第三章)
阿新 • • 發佈:2018-11-13
Feign-Hystrix
因為熔斷只是作用在服務呼叫這一端,因此我們根據上一篇的示例程式碼只需要改動spring-cloud-consumer專案相關程式碼就可以。因為,Feign中已經依賴了Hystrix所以在maven配置上不用做任何改動。
1、配置檔案
application.properties新增這一條:
feign.hystrix.enabled=true
2、建立回撥類
建立HelloRemoteHystrix類繼承與HelloRemote實現回撥的方法
@Component
public class HelloRemoteHystrix implements HelloRemote{
@Override
public String hello(@RequestParam(value = "name") String name) {
return "hello" +name+", this messge send failed ";
}
}
3、新增fallback屬性
在HelloRemote類新增指定fallback類,在服務熔斷的時候返回fallback類中的內容。
@FeignClient(name= "spring-cloud-producer",fallback = HelloRemoteHystrix. class)
public interface HelloRemote {
@RequestMapping(value = "/hello")
public String hello(@RequestParam(value = "name") String name);
}
改動點就這點,很簡單吧。
4、測試
那我們就來測試一下看看效果吧。
依次啟動0301spring-cloud-eureka、0302spring-cloud-producer、0303spring-cloud-consumer-hystrix三個專案。
瀏覽器中輸入:http://localhost:9091/hello/llx
返回:hello llx,this is first messge!
說明加入熔斷相關資訊後,不影響正常的訪問。接下來我們手動停止spring-cloud-producer專案再次測試:
瀏覽器中輸入:http://localhost:9091/hello/llx
返回:hello llx, this messge send failed!
根據返回結果說明熔斷成功。