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);
相关推荐
小马爱记录13 小时前
sentinel规则持久化
java·spring cloud·sentinel
小马爱记录16 小时前
Sentinel微服务保护
spring cloud·微服务·架构·sentinel
爱编程的张同学4 天前
OpenFeign和Gateway集成Sentinel实现服务降级
spring cloud·sentinel
运维老曾4 天前
Redis-6.2.9 Sentinel 哨兵配置
redis·sentinel
曼彻斯特的海边4 天前
spring-cloud-alibaba-sentinel-gateway
gateway·sentinel·springcloud
xujinwei_gingko4 天前
微服务-Sentinel
微服务·sentinel
_r0bin_9 天前
Sentinel
sentinel
LL小蜗牛9 天前
Alibaba Sentinel 入门教程:从理论到实战
sentinel
飞飞9879 天前
spring sentinel
java·spring·sentinel
cui_hao_nan9 天前
Sentinel限流熔断机制实战
java·sentinel