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

相关推荐
一只特立独行的猪6111 小时前
Java面试——集合篇
java·开发语言·面试
讓丄帝愛伱2 小时前
spring boot启动报错:so that it conforms to the canonical names requirements
java·spring boot·后端
weixin_586062022 小时前
Spring Boot 入门指南
java·spring boot·后端
雷袭月启2 小时前
SpringBoot实现OAuth客户端
spring boot·oauth客户端
Dola_Pan5 小时前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book5 小时前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
蜗牛^^O^6 小时前
Docker和K8S
java·docker·kubernetes
从心归零6 小时前
sshj使用代理连接服务器
java·服务器·sshj
IT毕设梦工厂8 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
Ylucius8 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习