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

相关推荐
田里的水稻35 分钟前
FA_排序算法-冒泡排序
java·算法·排序算法
会编程的吕洞宾2 小时前
Spring Cloud Gateway 限流鉴权与灰度发布实战
java·经验分享·后端·spring
AI开源软件3 小时前
SpringCloud+Nacos 业务协同落地:业务调用与集成中心远程管理如何分别配置
java·spring boot
sharemylove13 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
FYKJ_201013 小时前
springboot众创项目团队管理系统94666-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spark·课程设计
摇滚侠15 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 20
java·笔记·python
FYKJ_201018 小时前
springboot贫困生认定管理系统59009-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·后端·django·课程设计
考虑考虑18 小时前
JDK27中的结构化并发
java·后端·java ee
吃我一窝jio19 小时前
Java IO流核心分类与应用
java·开发语言·笔记
这个昵称不容易21 小时前
租房管理系统设计与实现:16 张表、185 个接口的 SpringBoot 前后台项目
java·springboot·毕设