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);
相关推荐
T_Ghost4 小时前
SpringCloud微服务服务容错机制Sentinel熔断器
spring cloud·微服务·sentinel
你是人间五月天1 天前
sentinel实现控制台与nacos数据双向绑定
windows·sentinel
无名客01 天前
sentinel限流常见的几种算法以及优缺点
算法·sentinel·限流
tsxchen1 天前
centos9安装sentinel
sentinel
寒士obj1 天前
Sentinel服务治理:服务降级、熔断与线程隔离
sentinel
iiYcyk1 天前
Hystrix与Sentinel-熔断限流
hystrix·sentinel·springcloud
勇往直前plus1 天前
Sentinel微服务保护
java·spring boot·微服务·sentinel
boy快快长大3 天前
【Spring Cloud Alibaba】Sentinel(一)
sentinel
java干货3 天前
Sentinel和Cluster,到底该怎么选?
sentinel
27^×3 天前
Sentinel 与 Feign 整合详解:实现服务调用的流量防护
sentinel