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

相关推荐
FQNmxDG4S34 分钟前
Maven依赖管理:版本冲突解决与生命周期控制
java·数据库·maven
傻瓜搬砖人1 小时前
Spring集成Web环境
java·spring·maven
FQNmxDG4S1 小时前
Java泛型编程:类型擦除与泛型方法的应用场景
java·开发语言·python
GottdesKrieges2 小时前
OceanBase恢复常见问题
java·数据库·oceanbase
IGAn CTOU2 小时前
Java高级开发进阶教程之系列
java·开发语言
leo825...2 小时前
Claude Code Skills 清单(本地)
java·python·ai编程
NGSI vimp2 小时前
Java进阶——如何查看Java字节码
java·开发语言
身如柳絮随风扬3 小时前
多数据源切换实战:从业务场景到3种实现方案全解析
java·分布式·微服务
Java小生不才3 小时前
Spring AI文生音
java·人工智能·spring
凯尔萨厮3 小时前
Springboot2.x+Thymeleaf项目创建
java