设置统一的hystrix fallback接口
- 前言
- Order工程改进(将fallback方法放到类中):即设置统一的hystrix fallback接口
- 1.不在方法上使用@HystrixCommand注解
- 2、创建回调类
- 3、在Feign客户端中添加fallback属性
- 4、配置文件中开启hystrix
- 5、重新启动应用测试
前言
一般在实际开发中fallback 方法不会直接写在接口方法所在类里,那样太杂乱,例如之前订单工程中的写法:
@HystrixCommand(fallbackMethod = "errorReturn")public Order createOrder3() {//1.创建订单对象Order order = new Order();order.setOid(100010);order.setUid(3309);List<Product> list = productFeignClient.list();order.setProductList(list);//2.返回return order;}private Order errorReturn() {return new Order(100010, 3309, Arrays.asList(new Product(1, "错误返回商品", new BigDecimal("0.0"))));}
Order工程改进(将fallback方法放到类中):即设置统一的hystrix fallback接口
1.不在方法上使用@HystrixCommand注解
//@HystrixCommand(fallbackMethod = "errorReturn")public Order createOrder4() {//1.创建订单对象Order order = new Order();order.setOid(100010);order.setUid(3309);List<Product> list = productFeignClient.list();order.setProductList(list);//2.返回return order;}
并在orderController中创建相应的调用方法
2、创建回调类
package com.oy.order.fallback;import com.oy.order.entity.Product;
import com.oy.order.feign.ProductFeignClient;
import org.springframework.stereotype.Component;import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;/*** @Description: 用一句话描述* @Date: 2020-11-04 11:27*/
@Component
public class ProductServiceFallback implements ProductFeignClient {@Overridepublic List<Product> list() {return Arrays.asList(new Product(1,"服务出问题了,商品查询错误",new BigDecimal("0.0")));}
}
3、在Feign客户端中添加fallback属性
package com.oy.order.feign;import com.oy.order.entity.Product;
import com.oy.order.fallback.ProductServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;import java.util.List;/*** 申明这是一个Feign客户端,并且指明服务id*/
@Component
@FeignClient(value = "service-product",fallback = ProductServiceFallback.class)//修改的地方在这里,内容为步骤2创建的文件名
public interface ProductFeignClient {/*** 这里定义了类似于SpringMVC用法的方法,就可以进行RESTful方式的调用了**/@RequestMapping(value = "/list", method = RequestMethod.GET)public List<Product> list();
}
4、配置文件中开启hystrix
#开启hystrix断路器
feign:hystrix:enabled: true