当重达到设定阀值时,还没有成功,那么就需要对日志进行统一打印,发出报警邮件,以便手动补偿或者感知异常。
@Recover
当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调。
在Retry标识的方法类中,加入以下方法:
@Recover
public void recover(RemoteAccessException e) {
logger.error(e.getMessage());//可以自定义日志内容
}
@Override
@SuppressWarnings("Duplicates")
@Retryable(value = {RemoteAccessException.class}, maxAttempts = 3, backoff = @Backoff(delay = 3000l, multiplier = 0))
public boolean customSendText(String openid, String content) throws RemoteAccessException {
String replyString = "{\n" +
"\"touser\":" + openid + ",\n" +
"\"msgtype\":\"text\",\n" +
"\"text\":\n" +
"{\n" +
"\"content\":" + content + "\n" +
"}\n" +
"}";
try {
logger.info("wx:customSend=request:{}", replyString.toString());
HttpsClient httpClient = HttpsClient.getAsyncHttpClient();
String url = Constant.WX_CUSTOM_SEND;
String token = wxAccessokenService.getAccessToken();
url = url.replace("ACCESS_TOKEN", token);
logger.info("wx:customSend=url:{}", url);
String string = httpClient.doPost(url, replyString);
logger.info("wx:customSend=response:{}", string);
if (StringUtils.isEmpty(string)) throw new RemoteAccessException("发送消息异常");
JSONObject jsonTexts = (JSONObject) JSON.parse(string);
if (jsonTexts.get("errcode") != null) {
String errcode = jsonTexts.get("errcode").toString();
if (errcode == null) {
throw new RemoteAccessException("发送消息异常");
}
if (Integer.parseInt(errcode) == 0) {
return true;
} else {
throw new RemoteAccessException("发送消息异常");
}
} else {
throw new RemoteAccessException("发送消息异常");
}
} catch (Exception e) {
logger.error("wz:customSend:{}", ExceptionUtils.getStackTrace(e));
throw new RemoteAccessException("发送消息异常");
}
}
注意:要触发@Recover方法,那么在@Retryable方法上不能有返回值,只能是void才能生效。
这样如果重试失败,就会有报警邮件发出,能够及时定位问题,便于处理。