Spring Cloud Alibaba整合Sentinel

一、需求

实现一个简单的 整合 sentinel,不涉及sentinel的用法

二、实现步骤

1、下载 sentinel dashboard

https://github.com/alibaba/Sentinel/releases
注意:

默认会启动8080端口,如果端口冲突,可以在启动命令上加入 -Dserver.port=新端口

默认用户名和密码[sentinel/sentinel]
启动控制台可用的配置项

2、服务提供者和消费者引入sentinel依赖

 <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

注意: 在这个里面查找 sentinel-core的版本号,可以确定我们需要下载那个版本的 sentinel dashboard

3、配置控制台信息

spring:
    sentinel:
      transport:
        # 控制台的地址
        dashboard: localhost:8080
        # 与控制台通讯的端口,默认是8719,不可用会一直+1,知道找到一个可用的
        port: 8719
        # 和控制台保持心跳的ip地址
        client-ip: 127.0.0.1
        # 发送心跳的周期,默认是10s
        heartbeat-interval-ms: 10000

4、一个简答的整合就整合完了,访问资源,查看控制台。

三、整合Feigen

1、配置文件中加入 feign.sentinel.enabled=true 即可。
2、加入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

3、对 Feign接口的降级或限流等操作时,资源名称的格式为:httpmethod:protocol://requesturl

四、整合 RestTemplate

1、在RestTemplate上加入 @SentinelRestTemplate注解。
2、配置文件中加入 resttemplate.sentinel.enabled: true,默认就是 true
3、降级或限流时的处理

抄sentinel的官网描述,文本给出链接

@SentinelRestTemplate 注解的属性支持限流(blockHandler, blockHandlerClass)和降级(fallback, fallbackClass)的处理。

其中 blockHandler 或 fallback 属性对应的方法必须是对应 blockHandlerClass 或 fallbackClass 属性中的静态方法。

该方法的参数跟返回值跟 org.springframework.http.client.ClientHttpRequestInterceptor#interceptor 方法一致,其中参数多出了一个 BlockException 参数用于获取 Sentinel 捕获的异常。

比如上述 @SentinelRestTemplate 注解中 ExceptionUtil 的 handleException 属性对应的方法声明如下:

public class ExceptionUtil {
    public static ClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException exception) {
        ...
    }
}

五、@SentinelResource的用法

1、@SentinelResource 注解用来标识资源是否被限流、降级。
2、一般推荐将 @SentinelResource 注解加到服务实现上
3、可以指定 blockHandlerfallback ,在发生异常时的处理。

六、代码路径

https://gitee.com/huan1993/spring-cloud-alibaba-parent/tree/master/sentinel

七、参考文档

Sentinel Wike
Sentinel 注解支持

猜你喜欢

转载自blog.csdn.net/fu_huo_1993/article/details/109271114