Loading

Rest实现熔断

Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护,在构造RestTemplate bean的时候需要加上 @SentinelRestTemplate 注解。
@Bean
@LoadBalanced
@SentinelRestTemplate(fallback = "handleFallback", fallbackClass =
ExceptionUtil.class,
blockHandler="handleBlock",blockHandlerClass=ExceptionUtil.class)
public RestTemplate getRestTemplate() {
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 SentinelClientHttpResponse handleBlock(HttpRequest request,
byte[] body,
ClientHttpRequestExecution
execution, BlockException ex) {
System.err.println("Oops: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("限流熔断降级");
}
//异常熔断业务逻辑
public static SentinelClientHttpResponse handleFallback(HttpRequest
request, byte[] body,
ClientHttpRequestExecution
execution, BlockException ex) {
System.err.println("fallback: " + ex.getClass().getCanonicalName());
return new SentinelClientHttpResponse("异常熔断降级");
}
}
Sentinel RestTemplate 限流的资源规则提供两种粒度:
  httpmethod:schema://host:port/path :协议、主机、端口和路径
  httpmethod:schema://host:port :协议、主机和端口
posted @ 2021-07-28 09:30  1640808365  阅读(124)  评论(0编辑  收藏  举报