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);
相关推荐
流烟默1 天前
网关 Sentinel 限流实战:API 分组、规则加载与全量匹配踩坑记
nacos·gateway·sentinel·流控规则
guo_wen_qiang5 天前
云服务器sentinel搭建-控制台
服务器·sentinel
guo_wen_qiang5 天前
项目使用sentinel遇到的问题
java·sentinel
天天喝旺仔21 天前
分布式服务容错实战:用 Sentinel 实现限流、熔断与降级
分布式·微服务·云原生·sentinel
YOU OU1 个月前
Alibaba Sentinel
sentinel
流烟默1 个月前
Sentinel 规则持久化到 Nacos 实践(网关篇 + 普通应用篇)
nacos·sentinel·规则持久化
莫得感情 o1 个月前
Redis 09 · 高可用:Sentinel 如何发现故障并完成切主
redis·缓存·sentinel
凌云若寒1 个月前
CODESOFT试用流程
linux·运维·网络·数据库·sentinel
多敲代码防脱发1 个月前
Alibaba Sentinel(熔断、限流)(国内下载Sentinel)
java·开发语言·sentinel
2601_962181961 个月前
【Spring Cloud Alibaba】Sentinel 服务熔断与流量控制
sentinel