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);

相关推荐
东阳马生架构6 分钟前
订单初版—2.生单链路中的技术问题说明文档
java
咖啡啡不加糖21 分钟前
暴力破解漏洞与命令执行漏洞
java·后端·web安全
风象南24 分钟前
SpringBoot敏感配置项加密与解密实战
java·spring boot·后端
DKPT34 分钟前
Java享元模式实现方式与应用场景分析
java·笔记·学习·设计模式·享元模式
Percep_gan42 分钟前
idea的使用小技巧,个人向
java·ide·intellij-idea
缘来是庄42 分钟前
设计模式之迭代器模式
java·设计模式·迭代器模式
Liudef061 小时前
基于HTML与Java的简易在线会议系统实现
java·前端·html
JosieBook1 小时前
【Java编程动手学】Java常用工具类
java·python·mysql
oioihoii1 小时前
C++11标准库算法:深入理解std::none_of
java·c++·算法
老虎06271 小时前
数据结构(Java)--位运算
java·开发语言·数据结构