bug记录——设置了feign的fallback,但是没有生效

问题描述

feign的代码

java 复制代码
package com.tianju.order.feign;

import com.tianju.order.feign.fallback.StorageFallback;
import com.tinaju.common.dto.GoodsDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "storage-server",fallback = StorageFallback.class)
public interface StorageFeign {
    @GetMapping("/findByCode")
    GoodsDto findByCommodityCode(@RequestParam("code") String code);

    @GetMapping("/subByCode")
    boolean subByCommodityCode(@RequestParam("code") String code,
                               @RequestParam("nums") Integer nums);
}

feign的fallback方法

java 复制代码
package com.tianju.order.feign.fallback;

import com.tianju.order.feign.StorageFeign;
import com.tinaju.common.dto.GoodsDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class StorageFallback implements StorageFeign {
    @Override
    public GoodsDto findByCommodityCode(String code) {
        return null;
    }

    @Override
    public boolean subByCommodityCode(String code, Integer nums) {
        log.info("调用减库存方法失败,商品编码为{},数量为{}",code,nums);

        return false;
    }
}

问题分析

查了一下别人的解决方案,有些人说是要打开hystrix的支持

yaml 复制代码
# 配置 Feign 远程调用
feign:
  hystrix:
    # 为 Feign 开启 Hystrix熔断机制,就可以使用回调
    enabled: true

我的配置文件里面确实没有加feig相关的依赖,但是我并没有是有hystrix,突然想到这个fallback既然是一个降级的方法,那必然需要有人负责调用它,而hystrix作为熔断降级的组件,应该就是负责这件事情的。

所以需要引入熔断降级的相关组件。

解决方案

我这里使用阿里巴巴的sentinel熔断降级工具,具体解决该问题的流程如下:

1.引入依赖

xml 复制代码
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

2.进行配置

yaml 复制代码
spring:
  # 激活common模块的配置,关于nacos等
  profiles:
    active: common

  # 项目名
  application:
    name: order-service


# 打开阿里的 sentinel
feign:
  sentinel:
    enabled: true

3.解决结果

总结

1.需要引入依赖,比如Hystrix,或者sentinel这样的熔断降级的组件;

2.进行配置,打开feign的支持;

3.正确写注解:@FeignClient(name = "storage-server",fallback = StorageFallback.class);

相关推荐
risc1234562 分钟前
DocumentsWriterDeleteQueue 的核心设计思想
java·全文检索·lucene
风味蘑菇干17 分钟前
Stream基础题目
java·算法
2501_9327502620 分钟前
Java反射机制基础入门
java·开发语言
5008428 分钟前
HCCL 集合通信编程:多卡协同的正确姿势
java·flutter·性能优化·electron·wpf
asdfg12589631 小时前
Java中的Comparator 和JS中的回调函数好相似
java·开发语言
会编程的土豆1 小时前
消息队列(MQ)入门笔记
java·笔记·spring
专注VB编程开发20年1 小时前
python运行提速方案全解
java·linux·服务器
涤生大数据1 小时前
大数据面试高频题:row_number() 数据倾斜到底怎么解决?
java·大数据·面试
weixin_446729161 小时前
注解和反射
java·开发语言
摇滚侠1 小时前
HashMap 源码解析 底层原理 面试如何回答
java·面试·职场和发展