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

相关推荐
qq_124987075312 分钟前
基于SpringBoot学生学习历史的选课推荐系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·学习·毕业设计·毕设
廋到被风吹走35 分钟前
【Spring】事务管理深度解析|从原理到实战
java·spring
lkbhua莱克瓦241 小时前
Java进阶——IO流
java·开发语言·笔记·学习方法·io流
韩立学长1 小时前
【开题答辩实录分享】以《自选便利店商品分类管理系统》为例进行选题答辩实录分享
java·mysql·web
阿杰同学1 小时前
Java中55种锁,高级面试题,最新面试题
java·开发语言
清晓粼溪1 小时前
SpringCloud01-基础概念
java·开发语言·spring cloud
路边草随风1 小时前
java实现发布flink yarn application模式作业
java·大数据·flink·yarn
华仔啊1 小时前
RabbitMQ 如何保证消息不丢失和不重复消费?掌握这 4 个关键点就够了
java·后端·rabbitmq
编程饭碗1 小时前
【Java循环】
java·服务器·算法
学到头秃的suhian2 小时前
SpringMVC的请求流程
java