国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Java > 正文

詳解spring cloud使用Hystrix實現(xiàn)單個方法的fallback

2024-07-13 10:17:18
字體:
供稿:網(wǎng)友

本文介紹了spring cloud-使用Hystrix實現(xiàn)單個方法的fallback,分享給大家,具體如下:

一、加入Hystrix依賴

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

二、編寫Controller

package com.chhliu.springboot.restful.controller;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;  import com.chhliu.springboot.restful.feignclient.UserFeignClient; import com.chhliu.springboot.restful.vo.User; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;  @RestController public class RestTemplateControllerHystrixCommand {      @Autowired   private UserFeignClient client; // 使用Feign來消費Restful服務(wù)      @GetMapping("/get/{id}")   @HystrixCommand(fallbackMethod="findByIdFallback")// 使用HystrixCommand注解,在fallbackMethod屬性中指定fallback的方法   public User findById(@PathVariable Long id) {     return client.findById(id);   }        // 覆寫fallbackMethod中指定的方法,注意,此方法的返回值,參數(shù)必須與原方法一致   public User findByIdFallback(Long id){     User u = new User();     u.setName("zhangsan");     u.setUsername("chhliu");     u.setId(9L);     return u;   } } 

三、在啟動類中添加Hystrix支持

@EnableCircuitBreaker 

四、添加配置文件

server.port:7904 # spring boot服務(wù)注冊到Eureka Server上的應(yīng)用名稱 spring.application.name=springboot-rest-template-feign-hystrix eureka.instance.prefer-ip-address=true # Eureka Server注冊服務(wù)的地址 eureka.client.service-url.defaultZone=http://chhliu:chhliu123456@localhost:8764/eureka springboot-h2.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RetryRule hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 1 #為了測試Hystrix的fallback效果,此處將超時時間設(shè)置成1毫秒 

五、測試

在瀏覽器中輸入:http://localhost:7904/get/2

測試結(jié)果如下:

{"id":9,"username":"chhliu","name":"zhangsan","age":null,"balance":null} 

從上面的測試結(jié)果可以看出,由于連接超時,直接進(jìn)入了fallback方法。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 临沭县| 黑水县| 泉州市| 舒城县| 江城| 嘉义县| 延吉市| 江山市| 平泉县| 开鲁县| 黎平县| 广东省| 山西省| 乃东县| 昭平县| 永嘉县| 巨鹿县| 益阳市| 云梦县| 建阳市| 渭源县| 青神县| 随州市| 山阳县| 永春县| 德昌县| 双城市| 龙南县| 文水县| 清远市| 息烽县| 新昌县| 霍林郭勒市| 闽清县| 公主岭市| 广饶县| 博客| 若羌县| 江永县| 云浮市| 杭锦旗|