sentinel使用手册

1.引入依赖

xml 复制代码
<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

2.yaml

yaml 复制代码
spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8090 #sentinel控制台地址
      http-method-specify: true # 是否设置请求方式作为资源名称
feign:
  sentinel:
    enabled: true # 开启feign对sentinel的支持

3.降级

3.1 引入依赖

xml 复制代码
<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

3.2 创建降级方案

触发限流或熔断后的请求不一定要直接报错,也可以返回一些默认数据或者友好提示,用户体验会更好。

给FeignClient编写失败后的降级逻辑有两种方式:

  • 方式一:FallbackClass,无法对远程调用的异常做处理
  • 方式二:FallbackFactory,可以对远程调用的异常做处理,我们一般选择这种方式。

这里我们演示方式二的失败降级处理。

步骤一:在hm-api模块中给ItemClient定义降级处理类,实现FallbackFactory

java 复制代码
@Component
public class ItemClientFallBackFactory implements FallbackFactory<ItemClient> {
    @Override
    public ItemClient create(Throwable cause) {
        return new ItemClient() {
            @Override
            public PageDTO<ItemDTO> queryItemByPage(PageQuery query) {
                //这里写降级逻辑
                return null;
            }

            @Override
            public List<ItemDTO> queryItemByIds(List<Long> ids) {
                //这里写降级逻辑
                return List.of();
            }
        };
    }
}

步骤二: 在hm-api模块中的ItemClient接口中使用ItemClientFallbackFactory:

java 复制代码
@FeignClient("item-service", fallbackFactory = ItemClientFallBackFactory.class)
public interface ItemClient {
    @GetMapping("/items/page")
    PageDTO<ItemDTO> queryItemByPage(PageQuery query);

    @GetMapping("/items")
    List<ItemDTO> queryItemByIds(@RequestParam("ids") List<Long> ids);
相关推荐
sniper_fandc1 天前
Spring Cloud系列—Alibaba Sentinel授权与规则管理及推送
spring cloud·sentinel
xiao-xiang2 天前
redis-sentinel基础概念及部署
数据库·redis·sentinel
Armyyyyy丶8 天前
Sentinel原理之责任链详解
java·sentinel·熔断限流
超人也会哭️呀10 天前
Redis(八):Redis高并发高可用(哨兵Sentinel)
redis·bootstrap·sentinel·哨兵·哨兵模式·高并发高可用
转身後 默落13 天前
14.Redis 哨兵 Sentinel
redis·bootstrap·sentinel
CHARLIIE17 天前
sentinel
sentinel
曹朋羽18 天前
spring cloud sentinel 动态规则配置
spring·spring cloud·sentinel
java叶新东老师21 天前
四、搭建springCloudAlibaba2021.1版本分布式微服务-加入openFeign远程调用和sentinel流量控制
分布式·微服务·sentinel
曹朋羽24 天前
Spring Cloud Alibaba Sentinel 基本工作原理源码阅读
sentinel
Zfox_1 个月前
Redis:哨兵(Sentinel)
服务器·数据库·redis·缓存·sentinel