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里面配置限流了。

相关推荐
京师20万禁军教头6 分钟前
28面向对象(中级)-封装
java
tERS ERTS18 分钟前
头歌答案--爬虫实战
java·前端·爬虫
识君啊24 分钟前
中小厂数据库事务高频面试题
java·数据库·mysql·隔离级别·数据库事务·acid
少许极端32 分钟前
算法奇妙屋(四十八)-单调栈
java·算法·单调栈
学习使我健康37 分钟前
Android 本地音乐播放(读取系统媒体库 + MediaPlayer)
java·android-studio
云烟成雨TD1 小时前
Spring AI Alibaba 1.x 系列【33】Human-in-the-Loop(人在回路)演示
java·人工智能·spring
難釋懷1 小时前
Redis服务器端优化-内存划分和内存配置
java·redis·spring
两年半的个人练习生^_^1 小时前
每日一学:设计模式之适配器模式
java·设计模式·适配器模式
程序员老邢1 小时前
【技术底稿 18】FTP 文件处理 + LibreOffice Word 转 PDF 在线预览 + 集群乱码终极排查全记录
java·经验分享·后端·pdf·word·springboot
磊 子1 小时前
类模板与派生1
java·开发语言·c++