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

相关推荐
吃饱了得干活8 分钟前
从0到1实现消息已读未读:从基础设计到高并发架构
java·后端·架构
r_oo_ki_e_8 分钟前
java微服务
java·微服务
weixin_BYSJ19879 分钟前
django在线图书销售平台---附源码16192
java·javascript·spring boot·python·django·flask·php
糖果店的幽灵10 分钟前
【langgraph 从入门到精通graphApi 篇】Command 与动态流程控制
android·java·数据库·人工智能·langgraph
只会CRUD的码仔12 分钟前
【踩坑记录】Thymeleaf 下拉框设置 disabled 变灰色,但依旧可以点击选择
java
减瓦12 分钟前
Java 8 编译器扩展点
java
_waylau23 分钟前
Spring Framework HTTP服务客户端详解
java·后端·网络协议·spring·http·spring cloud
蓝银草同学26 分钟前
Stream 数据统计实战:求和、平均值、分组汇总(AI 辅助学习 Java 8)
java·前端·后端
大模型丫丫39 分钟前
Skill-Agent 如何实践:从概念到落地的完整指南
java·大数据·人工智能
NWU_LK44 分钟前
【WebFlux】第四篇 —— 响应式异常处理与测试
java