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

相关推荐
nbsaas-boot12 分钟前
Go语言生态成熟度分析:为何Go还无法像Java那样实现注解式框架?
java·开发语言·golang
hi0_616 分钟前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
朝如青丝暮成雪_19 分钟前
java的三大特征
java
用户05956611920920 分钟前
Java 8 + 特性与 spring Boot 及 hibernate 等最新技术实操内容全解析
java·架构·设计
长安有故里y36 分钟前
tomcat设置预防host头攻击
java·tomcat·firefox
生产队队长37 分钟前
Tomcat问题:启动脚本startup.bat中文乱码问题解决
java·ajax·tomcat
张紫娃1 小时前
idea 常用快捷键
java·ide·intellij-idea
兮动人1 小时前
Java应用全链路故障排查实战指南:从系统资源到JVM深度诊断
java·开发语言·jvm
风流 少年1 小时前
Cursor创建Spring Boot项目
java·spring boot·后端
wáng bēn1 小时前
【java17】使用 Word 模板导出带替换符、动态表格和二维码的文档
java·word·itextpdf