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

相关推荐
饕餮争锋3 分钟前
Java泛型介绍
java·开发语言
程序媛徐师姐17 分钟前
Java基于SSM的即时空教室查询小程序,附源码+文档说明
java·微信小程序·小程序·ssm·即时空教室查询小程序·java即时空教室查询小程序·即时空教室查询微信小程序
努力长头发的程序猿20 分钟前
在Unity当中使用GameFrameworkX框架的知识点
java·unity·游戏引擎
季明洵30 分钟前
二叉树的最小深度、完全二叉树的节点个数、平衡二叉树、路径总和、从中序与后序遍历序列构造二叉树
java·数据结构·算法·leetcode·二叉树
AD钙奶-lalala1 小时前
SpringBoot 4.0.3配置Swagger
java·spring boot·后端
seven97_top1 小时前
NIO:解开非阻塞I/O高并发编程的秘密
java
小六溜了1 小时前
模块二十.双列集合
java
23.1 小时前
【Java】NIO 中的多路复用(Selector / Channel)机制
java·面试·nio
七夜zippoe1 小时前
Docker容器化实战:核心概念、镜像制作与多阶段构建全解析
java·jvm·数据库·docker·oracle·容器化
TimberWill1 小时前
优化if else过多的方案(含设计模式处理方式)
java·设计模式