Spring Cloud Alibaba之 Sentinel( 二 )

启动控制台Sentinel 控制台是一个标准的 SpringBoot 应用 , 以 SpringBoot 的方式运行 jar 包即可 。
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar如若8080端口冲突 , 可使用 -Dserver.port=新端口 进行设置 。
配置控制台信息spring:cloud:sentinel:transport:port: 8719dashboard: localhost:8080这里的 spring.cloud.sentinel.transport.port 端口配置会在应用对应的机器上启动一个 Http Server , 该 Server 会与 Sentinel 控制台做交互 。 比如 Sentinel 控制台添加了1个限流规则 , 会把规则数据 push 给这个 Http Server 接收 , Http Server 再将规则注册到 Sentinel 中 。
更多 Sentinel 控制台的使用及问题参考: Sentinel控制台
OpenFeign 支持Sentinel 适配了 OpenFeign 组件 。 如果想使用 , 除了引入 sentinel-starter 的依赖外还需要 2 个步骤:

  • 配置文件打开 sentinel 对 feign 的支持:feign.sentinel.enabled=true
  • 加入 openfeign starter 依赖使 sentinel starter 中的自动化配置类生效:
org.springframework.cloudspring-cloud-starter-openfeign这是一个 FeignClient 的简单使用示例:
@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)public interface EchoService {@GetMapping(value = "http://kandian.youth.cn/echo/{str}")String echo(@PathVariable("str") String str);}class FeignConfiguration {@Beanpublic EchoServiceFallback echoServiceFallback() {return new EchoServiceFallback();}}class EchoServiceFallback implements EchoService {@Overridepublic String echo(@PathVariable("str") String str) {return "echo fallback";}}Feign 对应的接口中的资源名策略定义:httpmethod:protocol://requesturl 。 @FeignClient 注解中的所有属性 , Sentinel 都做了兼容 。
EchoService 接口中方法 echo 对应的资源名为 GET:http://service-provider/echo/{str} 。
RestTemplate 支持Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护 , 在构造 RestTemplate bean的时候需要加上 @SentinelRestTemplate 注解 。
@Bean@SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class)public RestTemplate restTemplate() {return new RestTemplate();}@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) {...}}应用启动的时候会检查 @SentinelRestTemplate 注解对应的限流或降级方法是否存在 , 如不存在会抛出异常


推荐阅读