一、服務(wù)端
1、配置文件
application.yml
server: port: 9000 spring: application: name: my-test2 #服務(wù)的名稱
2、控制層
@RestController public class ShoppingController { @RequestMapping("/myTestBuy2") public String myTestBuy2(){ //用來模擬服務(wù)超時 try { Thread.sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } return "購買成功――時間:"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); } }
二、客戶端
1、依賴
<!--Open-Feign依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--hystrix依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2、配置文件
server: port: 8000 spring: application: name: my-test1 #服務(wù)的名稱 #允許服務(wù)降級配置 feign: hystrix: enabled: true #自定義ribbon的超時時間 設(shè)置的要比hystrix-timeoutInMilliseconds超時時間大 ribbon: #指的是建立連接后從服務(wù)器讀取到可用資源所用的時間。 ReadTimeout: 10000 #指的是建立連接所用的時間,適用于網(wǎng)絡(luò)狀況正常的情況下,兩端連接所用的時間,處理請求的超時時間,默認為5秒。 ConnectTimeout: 10000 hystrix: command: default: execution: isolation: thread: #feign整合hystrix 光設(shè)置Hystrix超時沒用的 要配合ribbon超時 timeoutInMilliseconds: 5000 my-test2: url: http://127.0.0.1:9000
3、啟動類
@SpringBootApplication @EnableFeignClients//開啟open-feign @EnableHystrix//開啟降級熔斷服務(wù) public class MyTestApplication1 { public static void main(String[] args) { SpringApplication.run(MyTestApplication1.class,args); } }
4、在控制層當(dāng)中調(diào)用
@RestController public class TestController1 { @Autowired TestService1 testService1; @RequestMapping("/myTestBuy1") public String myTestBuy2(){ return testService1.myTestBuy2(); } }
5、創(chuàng)建一個類實現(xiàn)服務(wù)FeignClient接口
@Component public class MyHystrix1 implements TestService1 { @Override public String myTestBuy2() { return "調(diào)用失敗,該服務(wù)被熔斷――時間:"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); } }
6、在服務(wù)FeignClient接口上配置FallBack實現(xiàn)類
@FeignClient(name = "my-test2", url = "${my-test2.url}", fallback = MyHystrix1.class) public interface TestService1 { @RequestMapping("/myTestBuy2") String myTestBuy2(); }
三、測試
1、場景一服務(wù)正常調(diào)用
2、場景二當(dāng)被調(diào)服務(wù)停止運行時
只給兩秒的時間,則自動啟動熔斷
3、場景三當(dāng)調(diào)取服務(wù)超時時
熔斷時間根據(jù)hystrix設(shè)置的時間,我這里設(shè)置的是5秒
4、其他
到此這篇關(guān)于Open-Feign整合hystrix降級熔斷實戰(zhàn)記錄的文章就介紹到這了,更多相關(guān)Open-Feign整合hystrix降級熔斷內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_46146718/article/details/120068091