针对springcloud 熔断与feign调用方式结合,fallback不生效的问题

针对springcloud 熔断与feign调用方式结合,fallback不生效的问题

最近自己在搭springcloud微服务的架构,在搭建过程中测试熔断功能踩了一个小坑,困扰了几个小时,最后终于解决了,下面我简单说明一下解决思路,话不多说先贴代码。

Controller

RestController
@RequestMapping("api/order")
public class ProductOrderController {

    @Autowired
    private ProductOrderImpl productOrder;

    @GetMapping("orderProduct")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id") int userId,@RequestParam("product_id") int product_id){
        System.err.println("user_id:"+userId);
        System.err.println("product_id:"+product_id);
        return  productOrder.save(userId,product_id);
    }

    public Object saveOrderFail(int userId,int product_id){
        Map<String,Object> map = new HashMap<>();
        map.put("code","1");
        map.put("msg","稍后再试,网络拥堵");
        return map;
    }

Service

  @Override
    public ProductOrder save(int userId, int productId) {
        //使用ribbon调用服务
        //Map map = restTemplate.getForObject("http://product-client/api/product/listById?id="+productId, Map.class);
        //System.out.println("map:-----------"+map);

        //使用feign调用服务,并把调用回来的结果保存在字符串中,使用json将结果解析
        String jsonStr = productClient.getProduct(productId);
        JsonNode jsonNode = JsonUtils.parseJson(jsonStr);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreateTime(new Date());
        productOrder.setTradeNo(UUID.randomUUID().toString());
        productOrder.setUserId(userId);
        productOrder.setProductName(jsonNode.get("name").toString());
        productOrder.setId(Integer.decode(jsonNode.get("id").toString()));
        productOrder.setPrice(Integer.decode(jsonNode.get("price").toString()));
        return productOrder;
    }

异常返回类的实现接口

@FeignClient(name="product-client",fallback = CutBreaker.class)
public interface ProductClient {

    @GetMapping("api/product/listById")
    public String getProduct(@RequestParam("id") int id);
}

熔断器实现

@Component
public class CutBreaker implements ProductClient {

    @Override
    public String getProduct(int id) {
        System.out.println("没有获取到该服务的任何消息!");
        return null;
    }

}

pom文件

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
			<version>2.1.3.RELEASE</version>
		</dependency>

从以上代码来看,写的并无问题,也尝试着 为什么请求后,无法达到熔断的效果,正常熔断触发后,会在控制台输出“不有获取到该服务的任何消息”这组数据

解决方法:
1、将application.yml配置文件中加入

feign:
  hystrix:
    enabled: true

2、如果方式1不生效,则将application.yml文件配置中加入

feign:
  circuitbreaker:
    enabled: true

你会发现,二者必有其一解决了你的问题,这是因为什么,这是因为springcloud在2.0后将熔断的属性做了更改。

你可能感兴趣的:(spring,cloud,java,spring,springboot)