RestTemplate的配置代码与你得代码一致
@Configuration
public class GatewayBeanConf {
@Bean
@SentinelRestTemplate(
blockHandlerClass = RestTemplateSentinelHandler.class, blockHandler = "handleBlock"
,fallbackClass = RestTemplateSentinelHandler.class, fallback = "handleFallback"
)
public RestTemplate restTemplate() {
// 使用factory对RestTemplate可以对其做一些业务相关的配置
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
// 建立连接超时时间 单位ms
factory.setConnectTimeout(15 * 1000);
// 传递数据的超时时间 单位ms
factory.setReadTimeout(5000);
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}
}
public class RestTemplateSentinelHandler {
/**
* 处理RestTemplate发送请求,因为限流原因抛出的BlockingException异常
* @param request // 请求信息
* @param body // 请求的参数信息
* @param requestExecution // 请求的链路信息
* @param exception // Sentinel限流触发后抛出的异常
* @return
*/
public static SentinelClientHttpResponse handleBlock(
HttpRequest request,
byte[] body,
ClientHttpRequestExecution requestExecution,
BlockException exception
) {
log.info("handle RestTemplate block exception, [{}] [{}]"
, request.getURI().getPath(), exception.getClass().getCanonicalName());
return new SentinelClientHttpResponse(
JSON.toJSONString(
new CommonResponse<String>(
-1,
"trigger RestTemplate handler block exception"
, request.getURI().getPath()
)
)
);
}
/**
* 异常降级之后的处理方法
* @param request
* @param body
* @param requestExecution
* @param exception
* @return
*/
public static SentinelClientHttpResponse handleFallback(
HttpRequest request,
byte[] body,
ClientHttpRequestExecution requestExecution,
BlockException exception
) {
log.info("handle RestTemplate fallback exception, [{}] [{}]"
, request.getURI().getPath(), exception.getClass().getCanonicalName());
return new SentinelClientHttpResponse(
JSON.toJSONString(
new CommonResponse<String>(
-1,
"trigger RestTemplate handler fallback exception"
, request.getURI().getPath()
)
)
);
}
}
在nacos的配置gateway-flow-rule-sentinel中,进行了以下的配置:
[
{
"resource": "health-cloud-sentinel",
"resourceMode": 0,
"count": 3,
"intervalSec": 10
},
{
"resource": "POST:http://10.10.102.134:7000/health-cloud-authority-center/authority/token",
"resourceMode": 0,
"count": 1,
"intervalSec": 60
},
{
"resource": "sentinel-client-api",
"resourceMode": 1,
"count": 5,
"intervalSec": 10
},
{
"resource": "health-cloud-cookbook-api",
"resourceMode": 1,
"count": 1,
"intervalSec": 50
}
]
在sentinel dashboard中配置也已经自动同步,如下图所示:
张老师给看一下,基于上述的配置,为什么RestTemplate的没有触发handlerBlock