Sentinel整合OpenFeign

1、配置文件

复制代码
feign:
  sentinel:
    enabled: true

2、 编写一个工厂类

java 复制代码
import com.cart.cartservice.client.ItemClient;
import com.cart.cartservice.entity.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.http.ResponseEntity;

@Slf4j
public class ItemClientFallbackFactory implements FallbackFactory<ItemClient> {

    @Override
    public ItemClient create(Throwable cause) {
        return new ItemClient() {
            @Override
            public ResponseEntity<Item> queryById(Integer id) {
                log.error("查询对象失败", cause);
                //返回一个空对象
                return ResponseEntity.ok(new Item());
            }
        };
    }
}

需要实现FallbackFactory接口,其中ItemClient为客户端接口。

3、声明这个类

java 复制代码
import com.cart.cartservice.factory.ItemClientFallbackFactory;
import org.springframework.context.annotation.Bean;

public class DefaultFeignConfig {

    @Bean
    public ItemClientFallbackFactory getItemClientFallbackFactory(){
        return new ItemClientFallbackFactory();
    }
}

4、ItemClient上添加openFeign注解的属性fallbackFactory = ItemClientFallbackFactory.class)

java 复制代码
import com.cart.cartservice.entity.Item;
import com.cart.cartservice.factory.ItemClientFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "item-service",fallbackFactory = ItemClientFallbackFactory.class)
public interface ItemClient {

    @GetMapping("item/{id}")
    ResponseEntity<Item> queryById(@PathVariable("id") Integer id);
}

这样就可以在Sentinel里面配置限流了。

相关推荐
南山十一少2 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
427724004 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo4 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦4 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个4 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
南宫生7 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
计算机毕设定制辅导-无忧学长7 小时前
Maven 基础环境搭建与配置(一)
java·maven
风与沙的较量丶8 小时前
Java中的局部变量和成员变量在内存中的位置
java·开发语言
m0_748251728 小时前
SpringBoot3 升级介绍
java
极客先躯10 小时前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分