详解spring cloud使用Hystrix实现单个方法的fallback
2018-01-26 11:11
756 查看
本文介绍了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方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- spring cloud-使用Hystrix实现单个方法的fallback
- 使用花生壳、路由器、个人电脑进行站点部署并实现外网域名访问图文详解(花生壳设置方法 使用方法 使用教程)
- STL源码剖析——deque的实现原理和使用方法详解
- STL源码剖析——stack的实现原理和使用方法详解
- 详解连接SQL Server数据库的方法,并使用Statement接口实现对数据库的增删改操作
- C#实现只运行单个实例应用程序的方法(使用VB.Net的IsSingleInstance)
- 使用C++实现全排列算法的方法详解
- iOS同一项目多个Target的快速实现方法 - 两种使用场景详解
- jQuery使用contains过滤器实现精确匹配方法详解
- Android中使用socket通信实现消息推送的方法详解
- JavaScript使用原型和原型链实现对象继承的方法详解
- 使用花生壳、路由器、个人电脑进行站点部署并实现外网域名访问图文详解(花生壳设置方法 使用方法 使用教程)
- JS使用正则截取两个字符串之间的字符串实现方法详解
- C#使用Object类实现栈的方法详解
- 使用DateTime的ParseExact方法实现特殊日期时间的方法详解(转)
- 详解CSS3中使用gradient实现渐变效果的方法
- PullScrollView详解(四)——完全使用listview实现下拉回弹(方法一)
- delphi WebBrowser的使用方法详解(四)-webbrowser轻松实现自动填表
- Angularjs使用directive自定义指令实现attribute继承的方法详解
- Data URI scheme详解和使用实例及图片base64编码实现方法