feign + hystrix 降级
Posted 程序餐厅
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了feign + hystrix 降级相关的知识,希望对你有一定的参考价值。
feign 启用 hystrix
feign 默认没有启用 hystrix,添加配置,启用 hystrix
feign.hystrix.enabled=true
application.yml 添加配置
feign:
hystrix:
true :
启用 hystrix 后,访问服务
http://localhost:3001/item-service/35
默认1秒会快速失败,没有降级方法时,会显示白板页
可以添加配置,暂时减小降级超时时间,以便后续对降级进行测试
......
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
feign + hystrix 降级
feign 远程接口中指定降级类
远程调用失败, 会执行降级类中的代码
ItemFeignService
...
public interface ItemFeignService {
...
UserFeignService
...
public interface UserFeignService {
...
OrderFeignService
...
@FeignClient(name="order-service",fallback = OrderFeignServiceFB.class)
public interface OrderFeignService {
...
降级类
降级类需要实现远程接口
ItemFeignServiceFB
package cn.tedu.sp09.service;
import java.util.List;
import org.springframework.stereotype.Component;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.web.util.JsonResult;
@Component
public class ItemFeignServiceFB implements ItemFeignService {
@Override
public JsonResult<List<Item>> getItems(String orderId) {
return JsonResult.err("无法获取订单商品列表");
}
@Override
public JsonResult decreaseNumber(List<Item> items) {
return JsonResult.err("无法修改商品库存");
}
}
UserFeignServiceFB
package cn.tedu.sp09.service;
import org.springframework.stereotype.Component;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
@Component
public class UserFeignServiceFB implements UserFeignService {
@Override
public JsonResult<User> getUser(Integer userId) {
return JsonResult.err("无法获取用户信息");
}
@Override
public JsonResult addScore(Integer userId, Integer score) {
return JsonResult.err("无法增加用户积分");
}
}
OrderFeignServiceFB
package cn.tedu.sp09.service;
import org.springframework.stereotype.Component;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.web.util.JsonResult;
@Component
public class OrderFeignServiceFB implements OrderFeignService {
@Override
public JsonResult<Order> getOrder(String orderId) {
return JsonResult.err("无法获取商品订单");
}
@Override
public JsonResult addOrder() {
return JsonResult.err("无法保存订单");
}
}
启动服务,访问测试
http://localhost:3001/item-service/35
以上是关于feign + hystrix 降级的主要内容,如果未能解决你的问题,请参考以下文章
SpringCloud+Eureka初识+Ribbon+Feign+Hystrix(服务熔断,服务降级)+hashbroad
springcloud feign + Hystrix 整合
跟我学Spring Cloud(Finchley版)-14-Feign使用Hystrix