用法
/**
* 重试器
*/
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());
}
}