詳解spring cloud使用Hystrix實現單個方法的fallback,hystrixfallback

來源:互聯網
上載者:User

詳解spring cloud使用Hystrix實現單個方法的fallback,hystrixfallback

本文介紹了spring cloud-使用Hystrix實現單個方法的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服務      @GetMapping("/get/{id}")   @HystrixCommand(fallbackMethod="findByIdFallback")// 使用HystrixCommand註解,在fallbackMethod屬性中指定fallback的方法   public User findById(@PathVariable Long id) {     return client.findById(id);   }        // 覆寫fallbackMethod中指定的方法,注意,此方法的傳回值,參數必須與原方法一致   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服務註冊到Eureka Server上的應用程式名稱 spring.application.name=springboot-rest-template-feign-hystrix eureka.instance.prefer-ip-address=true # Eureka Server註冊服務的地址 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效果,此處將逾時時間設定成1毫秒 

五、測試

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

測試結果如下:

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

從上面的測試結果可以看出,由於連線逾時,直接進入了fallback方法。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.