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

相关推荐
APIshop3 小时前
Java爬虫1688详情api接口实战解析
java·开发语言·爬虫
Evan芙3 小时前
Tomcat内存机制以及按场景调优
java·tomcat
总爱写点小BUG4 小时前
打印不同的三角形(C语言)
java·c语言·算法
星辰烈龙4 小时前
黑马程序员Java基础9
java·开发语言
山沐与山4 小时前
【Redis】Redis集群模式架构详解
java·redis·架构
ss2735 小时前
Java并发编程:DelayQueue延迟订单系统
java·python·算法
wcy_10115 小时前
七大软件设计原则
java·设计规范
invicinble5 小时前
jar包在执行的时候需要关注的细节(提供一个解构jvm问题的视角)
java·jvm·jar
麦芽糖02195 小时前
SSE介绍及使用(Server-Send Events)
java
alan07215 小时前
【Java + Elasticsearch全量 & 增量同步实战】
java·elasticsearch·jenkins