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

相关推荐
程序员小凯1 小时前
Spring Boot文件处理与存储详解
java·spring boot·后端
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 88: 环绕字符串中唯一的子字符串
java·数据结构·算法·leetcode·深度优先·动态规划
黑云压城After3 小时前
vue2实现图片自定义裁剪功能(uniapp)
java·前端·javascript
zcl_19914 小时前
记一次ThreadLocal导致的生产事故
java
RoboWizard4 小时前
怎么判断我的电脑是否支持PCIe 5.0 SSD?Kingston FURY Renegade G5
java·spring·智能手机·电脑·金士顿
毕设源码-钟学长5 小时前
【开题答辩全过程】以 儿童游泳预约系统为例,包含答辩的问题和答案
java·eclipse
皮皮林5515 小时前
5种接口频率监控方案实战对比,性能、成本、复杂度全解析!
java
似水流年 光阴已逝5 小时前
从Jar包到K8s上线:全流程拆解+高可用实战
java·kubernetes·jar
YA3336 小时前
java设计模式八、组合模式
java·设计模式·组合模式
一枚码仔6 小时前
SpringBoot启动时执行自定义内容的5种方法
java·spring boot·后端