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 Solon v3.3.0 发布(国产优秀应用开发基座)
java·spring·solon
不再幻想,脚踏实地3 分钟前
Spring Boot配置文件
java·数据库·spring boot
pedestrian_h11 分钟前
Spring AI 开发本地deepseek对话快速上手笔记
java·spring boot·笔记·llm·ollama·deepseek
诚丞成11 分钟前
BFS算法篇——从晨曦到星辰,BFS算法在多源最短路径问题中的诗意航行(上)
java·算法·宽度优先
亮11124 分钟前
GITLAB跑gradle项目 不借助maven-publish直接上传到nexus私人仓库
java·gitlab·gradle·maven
薯条不要番茄酱31 分钟前
【SpringBoot】从零开始全面解析Spring MVC (一)
java·spring boot·后端
翻滚吧键盘33 分钟前
idea中ctrl+/注释,总是出现在最前行
java·ide·intellij-idea
意倾城35 分钟前
JVM 如何优化 31 * x 为 (x << 5) - x?
java·jvm
醉殇姒若梦遗年2 小时前
怎么用idea打jar包
java·intellij-idea·jar
林九生2 小时前
【Docker】Docker环境下快速部署Ollama与Open-WebUI:详细指南
java·docker·eureka