详解spring cloud使用Hystrix实现单个方法的fallback
时间:2021-05-21 08:25:49|栏目:JAVA代码|点击: 次
本文介绍了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方法。
上一篇:Java中常见的陷阱题及答案
栏 目:JAVA代码
下一篇:详解Java的按位操作符
本文标题:详解spring cloud使用Hystrix实现单个方法的fallback
本文地址:http://www.codeinn.net/misctech/125748.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




