Spring Cloud Alibaba Sentinel 支持对 RestTemplate 的服务调用使用 Sentinel 进行保护,在构造RestTemplate bean的时候需要加上 @SentinelRestTemplate 注解。这样的话,所有的调用相当于都给加上了熔断降级的方法。
/
@SpringBootApplication@EntityScan("cn.itcast.order.entity")public class RestOrderApplication {/*** sentinel支持对restTemplate的服务调用使用sentinel方法.在构造* RestTemplate对象的时候,只需要加载@SentinelRestTemplate即可** 资源名:* httpmethod:schema://host:port/path :协议、主机、端口和路径* httpmethod:schema://host:port :协议、主机和端口** @SentinelRestTemplate:* 异常降级* fallback : 降级方法* fallbackClass : 降级配置类* 限流熔断* blockHandler* blockHandlerClass*/@LoadBalanced@Bean@SentinelRestTemplate(fallbackClass = ExceptionUtils.class,fallback = "handleFallback",blockHandler = "handleBlock" ,blockHandlerClass = ExceptionUtils.class)public RestTemplate restTemplate() {return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(RestOrderApplication.class,args);}}
2、自定义异常工具类:ExceptionUils
return的对象一定是前端需要的类型,以免报错。
public class ExceptionUtils {/*** 静态方法* 返回值: SentinelClientHttpResponse* 参数 : request , byte[] , clientRquestExcetion , blockException*///限流熔断业务逻辑public static SentinelClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) {return new SentinelClientHttpResponse("abc");}//异常降级业务逻辑public static SentinelClientHttpResponse handleFallback(HttpRequest request, byte[] body,ClientHttpRequestExecution execution, BlockException ex) {return new SentinelClientHttpResponse("def");}}
