Spring Retry重试失败日志打印-@Recover以及邮件通知

重试机制配置介绍:

当重达到设定阀值时,还没有成功,那么就需要对日志进行统一打印,发出报警邮件,以便手动补偿或者感知异常。

 

@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才能生效。

 

error级别日志邮件发送功能见:

这样如果重试失败,就会有报警邮件发出,能够及时定位问题,便于处理。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值