重试器(com.github.rholder:guava-retrying:2.0.0)

用法

/**
     * 重试器
     */
    private static final Retryer<Object> RETRYER = RetryerBuilder.newBuilder()
            .retryIfException()
            .retryIfResult(result -> {
                return result == null;
            })
            .withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS))
            .withStopStrategy(StopStrategies.stopAfterAttempt(15))
            .build();

在这里插入图片描述
使用
在这里插入图片描述

封装

package com.elecwatt.platform.retry;

import com.elecwatt.commons.resp.Response;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author suuyoo.wg on 2019/10/5
 */
@Component
public class RetryHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(RetryHelper.class);

    /**
     * 通用重试间隔毫秒数
     */
    private static final long NORMAL_INTERVAL = 10L;

    /**
     * 通用最大尝试次数
     */
    private static final int NORMAL_RETRY_TIMES = 10;

    private static final Retryer<Boolean> NORMAL_RETRYER = RetryerBuilder.<Boolean>newBuilder()
            .retryIfException()
            .retryIfResult(result -> {
                if (result == null) {
                    return true;
                }
                return !result;
            })
            .withWaitStrategy(WaitStrategies.fixedWait(NORMAL_INTERVAL, TimeUnit.MILLISECONDS))
            .withStopStrategy(StopStrategies.stopAfterAttempt(NORMAL_RETRY_TIMES))
            .build();


    public static Retryer<Boolean> getNormalRetryer() {
        return NORMAL_RETRYER;
    }

    public static Retryer<Object> getCustomizeRetryer(long timeout, int times) {
        return RetryerBuilder.newBuilder()
                .retryIfException()
                .retryIfResult(result -> {
                    if (result == null) {
                        return true;
                    } else {
                        Response result1 = (Response) result;
                        if (result1.isSuccess() && null == result1.getData()) {
                            return true;
                        }
                    }
                    return false;
                })
                .withWaitStrategy(WaitStrategies.fixedWait(timeout, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(times))
                .build();
    }

}

使用
在这里插入图片描述

 try {
//                private static final long NORMAL_INTERVAL = 3L;
//                private static final int NORMAL_RETRY_TIMES = 20;
                Object result = RetryHelper.getCustomizeRetryer(NORMAL_INTERVAL, NORMAL_RETRY_TIMES).call(() ->
                        ioTCoreDirectDeviceService.queryAsyncConfigDeviceTaskByParentOnlyResult(stringResponse.getData()));
                Response<List<IoTBizAsyncResultDTO>> resultResponse = (Response<List<IoTBizAsyncResultDTO>>) result;
                if (resultResponse.isSuccess()) {
                    List<IoTBizAsyncResultDTO> results = resultResponse.getData();
                    if (CollectionUtils.isNotEmpty(results)) {
                        for (IoTBizAsyncResultDTO ioTBizAsyncResultDTO : results) {
                            Object resultObj = ioTBizAsyncResultDTO.getResult();
                            if (resultObj instanceof Boolean && (Boolean) resultObj) {
                                taskResult = "配置成功";
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error("下任务超时: {}", request.getParentDevid());
                e.printStackTrace();
            }

响应封装

package com.elecwatt.commons.resp;

import com.elecwatt.commons.errors.WattError;
import com.elecwatt.commons.errors.WattException;
import com.elecwatt.commons.errors.enums.RpcErrorCodeEnum;
import com.elecwatt.commons.errors.enums.SystemErrorEnum;
import com.google.common.base.MoreObjects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
 * @author suuyoo.wg on 2019/10/7
 */
public class Response<T> implements Serializable {

    private static final long serialVersionUID = -6040682733757666131L;

    private static Logger LOGGER = LoggerFactory.getLogger(Response.class);

    private boolean success;
    private WattError error;
    private T data;

    public Response() {
    }

    public Response(WattError error) {
        this.success = false;
        this.error = error;
    }

    public Response(T data) {
        this.success = true;
        this.data = data;
    }

    /**
     * 判定响应正确
     *
     * @param response
     */
    public static void assertSuccess(Response response) {
        if (response == null) {
            LOGGER.error("[接口响应结果为空]");
            throw new WattException(SystemErrorEnum.NPE_ERROR.getError("response"));
        }

        if (!response.isSuccess()) {
            LOGGER.error("[接口响应异常]:{}", response.getError());
            throw new WattException(response.getError());
        }
    }

    /**
     * 判定响应正确
     *
     * @param response
     */
    public static void assertSuccessData(Response response) {
        if (response == null) {
            LOGGER.error("[接口响应结果为空]");
            throw new WattException(SystemErrorEnum.NPE_ERROR.getError("response"));
        }

        if (!response.isSuccess()) {
            LOGGER.error("[接口响应异常]:{}", response.getError());
            throw new WattException(response.getError());
        }

        if (null == response.getData()) {
            // todo 打印接口名或者url
            LOGGER.error("[接口未查询到数据]");
            throw new WattException(new WattError("", "", "数据异常,未查询到该数据"));
        }
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public WattError getError() {
        return error;
    }

    public void setError(WattError error) {
        this.error = error;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("data", data)
                .add("error", error)
                .add("success", success)
                .toString();
    }

    /**
     * 判断rpc返回的response对象,是否包含以下异常,若包含返回对应WattError。
     * response=null
     * response.success=false & response.error=null
     * 若response.success=true,返回null。
     * @param response
     * @return WattError
     */
    public static WattError checkRpcError(Response response){
        return checkRpcError(response, false);
    }

    /**
     * 判断rpc返回的response对象,是否包含以下异常,若包含返回对应WattError。
     * response=null
     * response.success=false & response.error=null
     * 若response.success=true,返回null。
     * @param response
     * @param returnSourceError response含有异常信息前提下,是否返回原异常信息。
     * @return WattError
     */
    public static WattError checkRpcError(Response response, boolean returnSourceError){
        if(null == response){
            return RpcErrorCodeEnum.NULL_RESPONSE.getError();
        }
        if(response.isSuccess()){
            return null;
        }
        WattError error = response.getError();
        if(null == error){
            return RpcErrorCodeEnum.UNKNOWN_ERROR_RESPONSE.getError();
        }

        if(returnSourceError){
            return error;
        }
        return RpcErrorCodeEnum.ERROR_RESPONSE.getError(error.getCode(), error.getView());
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值