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

相关推荐
lgbisha5 分钟前
银河麒麟入门:日志刷满终端,用 less 定位关键词并看前后几行
java·前端·less·银河麒麟
xpbobcsdn5 分钟前
JDK 28 值类:省一半内存,慢三成
java·开发语言
Monkey的自我迭代17 分钟前
Kubernetes 声明式理念:只写“我要什么”
java·学习·kubernetes
Shaoshing26 分钟前
LeetCode 1798. 你能构造出连续值的最大数目
java·数据结构·算法
源码_空间1 小时前
基于SpringBoot的在线技能闯关与数字徽章平台(源码+文档)
java·spring boot·后端
不会画画的画师1 小时前
Spring IOC
java·后端·spring
泡海椒1 小时前
Java PDF 报表开发:仓储入库单从版式评审到落地的完整问答
java·开发语言·pdf
SunnyDays10111 小时前
Java 填充 Excel 模板:用命名区域告别写死的单元格地址
java·excel
泡海椒2 小时前
Java PDF 报表开发:城东新区交通枢纽项目的里程碑排期,从 FlightData 到进度通报 PDF
java·开发语言·pdf
比特屿2 小时前
Spring AI 2.1实战(七):RAG上篇,把私有文档喂给模型
java·后端