在基于sentinel 的服务保护上一文中,我们通过restTemplate来请求服务提供者,然后通过@SentinelResource 来使用sentinel的降级,如果我们要调用多个http 请求,就需要配置多个降级方法,代码臃肿。所以可以配置一个公用的降级,熔断方法。
@GetMapping("/buy/{id}")
@SentinelResource(value="order",blockHandler = "orderblockHandler",fallback
= "orderfallback")
public Product order(@PathVariable Long id) {
return restTemplate.getForObject("http://shop-service-
product/product/1", Product.class);
}
一,在restTemplate 的bean 上加上注解
Spring Cloud Alibaba Sentinel
支持对
RestTemplate
的服务调用使用
Sentinel
进行保护,在构造
RestTemplate
bean
的时候需要加上
@SentinelRestTemplate
注解。
- @SentinelRestTemplate 注解的属性支持限流( blockHandler , blockHandlerClass )和降级 ( fallback , fallbackClass )的处理。
- 其中 blockHandler 或 fallback 属性对应的方法必须是对应 blockHandlerClass 或 fallbackClass 属性中的静态方法。
- 该方法的参数跟返回值跟org.springframework.http.client.ClientHttpRequestInterceptor#interceptor 方法一致,其中参数多出了一个 BlockException 参数用于获取 Sentinel 捕获的异常。
@SpringBootApplication
@EntityScan("com.zjk.feignHystrix.entity")
@EnableEurekaClient
//通过@EnableFeignClients 激活feign
@EnableFeignClients
//激活hystrix
@EnableHystrix
@EnableCircuitBreaker
@EnableHystrixDashboard
public class OrdFeignSentinelApplication {
@Bean
@LoadBalanced
@SentinelRestTemplate(fallback = "handleFallback",fallbackClass = ExceptionUtil.class, blockHandler="handleBlock",blockHandlerClass=ExceptionUtil.class)
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrdFeignSentinelApplication.class,args);
}
}
比如上述
@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 :协议、主机和端口