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

相关推荐
码界奇点2 分钟前
Java Web学习 第1篇前端基石HTML 入门与核心概念解析
java·前端·学习·xhtml
.ZGR.5 分钟前
蓝桥杯高校新生编程赛第二场题解——Java
java·算法·蓝桥杯
陈果然DeepVersion8 分钟前
Java大厂面试真题:Spring Boot+Kafka+AI智能客服场景全流程解析(四)
java·spring boot·微服务·kafka·面试题·rag·ai智能客服
好学且牛逼的马19 分钟前
【JavaWeb|day16 Web前端基础】
java
haofafa38 分钟前
高精度加减法
java·数据结构·算法
huihuihuanhuan.xin40 分钟前
后端八股之消息队列
java·rabbitmq
渡我白衣1 小时前
C++世界的混沌边界:undefined_behavior
java·开发语言·c++·人工智能·深度学习·语言模型
88Ra1 小时前
Spring Boot 3.3新特性全解析
java·spring boot·后端
你知道“铁甲小宝”吗丶1 小时前
【第37章】Spring Cloud之Spring Cloud Stream分布式消息队列
spring cloud
剑海风云1 小时前
JDK 26:HTTP/3 支持已可在 HTTP 客户端 API 中使用
java·开发语言·http