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 小时前
汽车零件厂如何通过 QMS 真正落地 IATF 16949——QMS软件系统:品质检验-内审稽核-8d客诉管理:全星质量管理软件系统
java·前端·数据库
QCoding8 小时前
Spring AI Alibaba Graph实战:从ReAct Agent到Workflow,企业AI复杂流程该如何编排?
java·人工智能
用户094248568038 小时前
第25章:Java虚拟线程(Project Loom)实战与调度协作
java·jvm
砚底藏山河8 小时前
量化实战:截面因子有效性检验(IC 分析与分层回测)
java·python·金融·maven
wuminyu8 小时前
ForkJoinPool内部WorkQueue的Lock-Free数组操作以及并发任务窃取原理剖析
java·linux·c语言·jvm·c++
Elastic 中国社区官方博客8 小时前
使用 Lucene 搜索你的 Bean — 索引
java·大数据·数据库·elasticsearch·搜索引擎·全文检索·lucene
code2cat8 小时前
Java进阶篇之AtomicMarkableReference:引用还在,标记已经改变
java·开发语言·cas·并发编程·逻辑删除
她说彩礼65万8 小时前
C语言 堆区和栈区
java·linux·c语言
Zguigo8 小时前
【CUDA8】第一个CUDA C++ Kernel --vector add
java·开发语言·c++
一技安身9 小时前
【java】JDK8 + JDK17 绿色解压共存方案-全程不修改任何系统环境变量
java·开发语言