0 Star 0 Fork 0

浪子花梦 / 技术文章收录

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
连接异常及并发异常重试.md 2.70 KB
一键复制 编辑 原始数据 按行查看 历史
/**
 * 连接异常标记
 *
 * @author ithuameng
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConnectionRetry {

}

/**
 * 连接异常重试切面类
 *
 * @author ithuameng
 */
@Component
@Aspect
public class ConnectionAspect {

    private static final int MAX_RETRIES = 3;

    @Around("@annotation(ConnectionRetry)")
    public Object tryCount(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        int numAttempts = 0;
        boolean isDone;
        do {
            isDone = false;
            numAttempts++;
            try {
                result = joinPoint.proceed();
                isDone = true;
            } catch (SocketException e) {
                System.out.println("连接异常,准备进行第" + numAttempts + "次重试!");
            }
        } while (numAttempts < MAX_RETRIES && !isDone);
        if (!isDone) {
            throw new BlsException(CommonError.BIZ_ERR, "连接超时!");
        }
        return result;
    }
}
/**
 * 乐观锁标记
 *
 * @author ithuameng
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Locker {

}

/**
 * 并发重试标记
 *
 * @author ithuameng
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConcurrentRetry {

}

/**
 * 乐观锁并发重试切面类
 *
 * @author ithuameng
 */
@Component
@Aspect
public class ConcurrentLockerAspect {

    private static final int MAX_RETRIES = 2;

    @Around("@annotation(ConcurrentRetry)")
    public Object tryCount(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        ConcurrentException concurrentException = null;
        int numAttempts = 0;
        boolean isDone;
        do {
            isDone = false;
            numAttempts++;
            try {
                result = joinPoint.proceed();
                isDone = true;
            } catch (ConcurrentException exception) {
                concurrentException = exception;
                System.out.println(numAttempts + " attempt...");
            }
        } while (numAttempts < MAX_RETRIES && !isDone);
        if (!isDone) {
            System.out.println("attempt " + MAX_RETRIES + " times but not work!");
            throw concurrentException;
        }
        return result;
    }

    @AfterReturning(value = "@annotation(Locker)", returning = "returnValue")
    public void doAfterReturning(int returnValue) {
        if (returnValue == 0) {
            throw new ConcurrentException();
        }
    }
}
1
https://gitee.com/ithuameng/blog.git
git@gitee.com:ithuameng/blog.git
ithuameng
blog
技术文章收录
master

搜索帮助