码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 基于Spring-AOP的自定义分片工具


    作者:陈昌浩

    1 背景

    随着数据量的增长,发现系统在与其他系统交互时,批量接口会出现超时现象,发现原批量接口在实现时,没有做分片处理,当数据过大时或超过其他系统阈值时,就会出现错误。由于与其他系统交互比较多,一个一个接口做分片优化,改动量较大,所以考虑通过AOP解决此问题。

    2 Spring-AOP

    AOP (Aspect Orient Programming),直译过来就是 面向切面编程。AOP 是一种编程思想,是面向对象编程(OOP)的一种补充。面向对象编程将程序抽象成各个层次的对象,而面向切面编程是将程序抽象成各个切面。

    Spring 中的 AOP 是通过动态代理实现的。 Spring AOP 不能拦截对对象字段的修改,也不支持构造器连接点,我们无法在 Bean 创建时应用通知。

    3 功能实现

    自定义分片处理分三个部分:自定义注解(MethodPartAndRetryer)、重试器(RetryUtil)、切面实现(RetryAspectAop)。

    3.1 MethodPartAndRetryer

    源码

    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface MethodPartAndRetryer {
    /**
    * 失败重试次数
    * @return
    */
    int times() default 3;
    /**
    * 失败间隔执行时间 300毫秒
    * @return
    */
    long waitTime() default 300L;
    /**
    * 分片大小
    * @return
    */
    int parts() default 200;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    @interface说明这个类是个注解。
    @Target是这个注解的作用域

     
    public enum ElementType {
    /** 类、接口(包括注释类型)或枚举声明 */
    TYPE,
    /** 字段声明(包括枚举常量) */
    FIELD,
    /** 方法声明 */
    METHOD,
    /** 正式的参数声明 */
    PARAMETER,
    /** 构造函数声明 */
    CONSTRUCTOR,
    /** 局部变量声明 */
    LOCAL_VARIABLE,
    /** 注释类型声明*/
    ANNOTATION_TYPE,
    /** 程序包声明 */
    PACKAGE,
    /**类型参数声明*/
    TYPE_PARAMETER,
    /**类型的使用*/
    TYPE_USE
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    @Retention注解的生命周期

    public enum RetentionPolicy {
    /** 编译器处理完后不存储在class中*/
    SOURCE,
    /**注释将被编译器记录在类文件中,但不需要在运行时被VM保留。 这是默认值*/
    CLASS,
    /**编译器存储在class中,可以由虚拟机读取*/
    RUNTIME
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • times():接口调用失败时,重试的次数。
    • waitTime():接口调用失败是,间隔多长时间再次调用。
    • int parts():进行分片时,每个分片的大小。

    3.2 RetryUtil

    源码

    public class RetryUtil {
    
    public Retryer getDefaultRetryer(int times,long waitTime) {
    Retryer retryer = RetryerBuilder.newBuilder()
    .retryIfException()
    .retryIfRuntimeException()
    .retryIfExceptionOfType(Exception.class)
    .withWaitStrategy(WaitStrategies.fixedWait(waitTime, TimeUnit.MILLISECONDS))
    .withStopStrategy(StopStrategies.stopAfterAttempt(times))
    .build();
    return retryer;
    }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    说明

    • RetryerBuilder:是用于配置和创建Retryer的构建器。
    • retryIfException:抛出runtime异常、checked异常时都会重试,但是抛出error不会重试。
    • retryIfRuntimeException:只会在抛runtime异常的时候才重试,checked异常和error都不重试。
    • retryIfExceptionOfType:允许我们只在发生特定异常的时候才重试。
    • withWaitStrategy:等待策略,每次请求间隔。
    • withStopStrategy:停止策略,重试多少次后停止。
    3.3 RetryAspectAop

    源码:

    public class RetryAspectAop {
    public Object around(final ProceedingJoinPoint point) throws Throwable {
    Object result = null;
    final Object[] args = point.getArgs();
    boolean isHandler1 = isHandler(args);
    if (isHandler1) {
    String className = point.getSignature().getDeclaringTypeName();
    String methodName = point.getSignature().getName();
    Object firstArg = args[0];
    List paramList = (List) firstArg;
    //获取方法信息
    Method method = getCurrentMethod(point);
    //获取注解信息
    MethodPartAndRetryer retryable = AnnotationUtils.getAnnotation(method, MethodPartAndRetryer.class);
    //重试机制
    Retryer retryer = new RetryUtil().getDefaultRetryer(retryable.times(),retryable.waitTime());
    //分片
    List> requestList = Lists.partition(paramList, retryable.parts());
    for (List partList : requestList) {
    args[0] = partList;
    Object tempResult = retryer.call(new Callable() {
    @Override
    public Object call() throws Exception {
    try {
    return point.proceed(args);
    } catch (Throwable throwable) {
    log.error(String.format("分片重试报错,类%s-方法%s",className,methodName),throwable);
    throw new RuntimeException("分片重试出错");
    }
    }
    });
    if (null != tempResult) {
    if (tempResult instanceof Boolean) {
    if (!((Boolean) tempResult)) {
    log.error(String.format("分片执行报错返回类型不能转化bolean,类%s-方法%s",className,methodName));
    throw new RuntimeException("分片执行报错!");
    }
    result = tempResult;
    } else if (tempResult instanceof List) {
    if(result ==null){
    result =Lists.newArrayList();
    }
    ((List) result).addAll((List) tempResult);
    }else {
    log.error(String.format("分片执行返回的类型不支持,类%s-方法%s",className,methodName));
    throw new RuntimeException("不支持该返回类型");
    }
    } else {
    log.error(String.format("分片执行返回的结果为空,类%s-方法%s",className,methodName));
    throw new RuntimeException("调用结果为空");
    }
    }
    } else {
    result = point.proceed(args);
    }
    return result;
    }
    private boolean isHandler(Object[] args) {
    boolean isHandler = false;
    if (null != args && args.length > 0) {
    Object firstArg = args[0];
    //如果第一个参数是list 并且数量大于1
    if (firstArg!=null&&firstArg instanceof List &&((List) firstArg).size()>1) {
    isHandler = true;
    }
    }
    return isHandler;
    }
    private Method getCurrentMethod(ProceedingJoinPoint point) {
    try {
    Signature sig = point.getSignature();
    MethodSignature msig = (MethodSignature) sig;
    Object target = point.getTarget();
    return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
    } catch (NoSuchMethodException e) {
    throw new RuntimeException(e);
    }
    }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    说明:

    getCurrentMethod:获取方法信息即要做分片的批量调用的接口。
    isHandler1:判断是否要做分片处理,只有第一参数是list并且list 的值大于1时才做分片处理。
    around:具体分片逻辑。

    1. 获取要分片方法的参数。
    2. 判断是否要做分片处理。
    3. 获取方法。
    4. 获取重试次数、重试间隔时间和分片大小。
    5. 生成重试器。
    6. 根据设置的分片大小,做分片处理。
    7. 调用批量接口并处理结果。

    4 功能使用

    4.1 配置文件

    在这里插入图片描述

    4.2 代码示例
    @MethodPartAndRetryer(parts=100)
    public Boolean writeBackOfGoodsSN(List listSerial,ObCheckWorker workerData)
    
    
    
    • 1
    • 2
    • 3
    • 4

    只要在需要做分片的批量接口方法上,加上MethodPartAndRetryer注解就可以,重试次数、重试间隔时间和分片大小可以在注解时设置,也可以使用默认值。

    5 小结

    通过自定义分片工具,可以快速的对老代码进行分片处理,而且增加了重试机制,提高了程序的可用性,提高了对老代码的重构效率。

  • 相关阅读:
    王道机试C++第 5 章 数据结构二:队列queue和21年蓝桥杯省赛选择题Day32
    基于Java+SpringBoot+Vue线上医院挂号系统的设计与实现 前后端分离【Java毕业设计·文档报告·代码讲解·安装调试】
    python——Django框架
    Mysql第四篇---数据库索引优化与查询优化
    uniapp滚动加载
    SpringBoot如何自定义拦截器呢?
    centos or redhat?
    lc marathon 8.2
    超详细讲解H5移动端适配
    快速认识 WebAssembly
  • 原文地址:https://blog.csdn.net/jdcdev_/article/details/127978654
    • 最新文章
    • 攻防演习之三天拿下官网站群
      数据安全治理学习——前期安全规划和安全管理体系建设
      企业安全 | 企业内一次钓鱼演练准备过程
      内网渗透测试 | Kerberos协议及其部分攻击手法
      0day的产生 | 不懂代码的"代码审计"
      安装scrcpy-client模块av模块异常,环境问题解决方案
      leetcode hot100【LeetCode 279. 完全平方数】java实现
      OpenWrt下安装Mosquitto
      AnatoMask论文汇总
      【AI日记】24.11.01 LangChain、openai api和github copilot
    • 热门文章
    • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
      奉劝各位学弟学妹们,该打造你的技术影响力了!
      五年了,我在 CSDN 的两个一百万。
      Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
      面试官都震惊,你这网络基础可以啊!
      你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
      心情不好的时候,用 Python 画棵樱花树送给自己吧
      通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
      13 万字 C 语言从入门到精通保姆级教程2021 年版
      10行代码集2000张美女图,Python爬虫120例,再上征途
    Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
    正则表达式工具 cron表达式工具 密码生成工具

    京公网安备 11010502049817号