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

相关推荐
程序员清风9 分钟前
北京回长沙了,简单谈谈感受!
java·后端·面试
何中应18 分钟前
请求头设置没有生效
java·后端
亓才孓43 分钟前
[JDBC]批处理
java
春日见1 小时前
车辆动力学:前后轮车轴
java·开发语言·驱动开发·docker·计算机外设
宋小黑1 小时前
JDK 6到25 全版本网盘合集 (Windows + Mac + Linux)
java·后端
7哥♡ۣۖᝰꫛꫀꪝۣℋ1 小时前
Spring-cloud\Eureka
java·spring·微服务·eureka
老毛肚1 小时前
手写mybatis
java·数据库·mybatis
两点王爷1 小时前
Java基础面试题——【Java语言特性】
java·开发语言
choke2331 小时前
[特殊字符] Python 文件与路径操作
java·前端·javascript
choke2332 小时前
Python 基础语法精讲:数据类型、运算符与输入输出
java·linux·服务器