spring schedule轻量级分布式调度方案--实现

接上文https://blog.csdn.net/weixin_43493520/article/details/107877905,介绍不再多说。

类结构图例

类结构图例

代码

OnceOnTheSameTime

/**
 * 业务语义的背景下,同一时刻,只能执行一次
 * 1. spring schedule,暂不支持分布式调度,提供轻量级分布式锁控制组件,解决这个问题
 * 2. 用户界面重复点击,创建同一条记录时,防重复,统一处理。
 * 3. 消息队列的幂等处理
 *
 **/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OnceOnTheSameTime {

    /**
     * 定义once的有效期。
     */
    int timeoutInSeconds() default 30;

    /**
     * 定义重复的key: 使用SpEL语法。
     * 单参数举例:  name.concat('.').concat(age)
     * 多参数举例:  #args[0].name + '.' +#args[0].age
     */
    String keyDefinition() default "";
}

AbstractOnceService

 @Slf4j
public class AbstractOnceService {
    private static final String LOCK = "1";
    public static final String DOT = ".";
    public static final String ARGS = "args";

    @Value("${app.id}")
    private String appName;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public Object aroundInvoke(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        OnceOnTheSameTime anno = AnnotationUtils.getAnnotation(method, OnceOnTheSameTime.class);
        int timeoutInSeconds = anno.timeoutInSeconds();
        String key = constructKey(joinPoint, anno);

        boolean locked = lock(key, timeoutInSeconds);
        log.info("once aspect around invoked, redis key:{}, locked result:{}", key, locked);
        if (locked) {
            try {
                return joinPoint.proceed();
            } finally {
                unlock(key);
            }
        }

        throw new CommonException("repeated-execution", "重复执行");
    }

    private boolean lock(String key, int timeoutInSeconds) {
        return redisTemplate.opsForValue().setIfAbsent(key, LOCK, timeoutInSeconds, TimeUnit.SECONDS);
    }

    protected void unlock(String key) {
        redisTemplate.delete(key);
    }

    protected String constructKey(ProceedingJoinPoint joinPoint, OnceOnTheSameTime anno) {
        Object[] args = joinPoint.getArgs();

        if (args == null || args.length == 0) {
            return constructNoArgKey(joinPoint, anno);
        }

        if (args.length == 1) {
            return constructOneArgKey(joinPoint, anno, args[0]);
        }

        return constructMoreArgKey(joinPoint, anno, args);
    }

	/**
     * 构造多参数key
     *
     * @param joinPoint
     * @param anno
     * @param args
     * @return
     */
    private String constructMoreArgKey(ProceedingJoinPoint joinPoint, OnceOnTheSameTime anno, Object[] args) {

        StringBuilder keyBuilder = new StringBuilder(appName).append(DOT);
        EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
        context.setVariable(ARGS, args);

        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(anno.keyDefinition());
        String value = expression.getValue(context, String.class);
        keyBuilder.append(value);

        return keyBuilder.toString();
    }

    /**
     * 构造一个参数的key
     *
     * @param joinPoint
     * @param anno
     * @param arg
     * @return
     */
    private String constructOneArgKey(ProceedingJoinPoint joinPoint, OnceOnTheSameTime anno, Object arg) {
        StringBuilder keyBuilder = new StringBuilder(appName).append(DOT);

        SpelExpressionParser parser = new SpelExpressionParser();
        Expression expression = parser.parseExpression(anno.keyDefinition());
        Object value = expression.getValue(arg);
        keyBuilder.append(value);

        return keyBuilder.toString();
    }

    /**
     * 构造无参数的key
     *
     * @param joinPoint
     * @param anno
     * @return
     */
    private String constructNoArgKey(ProceedingJoinPoint joinPoint, OnceOnTheSameTime anno) {
        StringBuilder keyBuilder = new StringBuilder(appName).append(DOT);

        Object target = joinPoint.getTarget();
        //得到其方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        String keyDefination = anno.keyDefinition();
        //处理无参数key定义
        String keySuffix = StringUtils.isBlank(keyDefination) ? target.getClass().getSimpleName() + "." + method.getName() : keyDefination;
        return keyBuilder.append(keySuffix).toString();
    }


}

MessageIdempotenceOnceService

/**
 * 消息队列的幂等处理*
 **/
@Component
@Slf4j
public class MessageIdempotenceOnceService extends AbstractOnceService {

    @Override
    protected void unlock(String key) {
        // do nothing..
    }

}

}


OnceOnTheSameTimeAspect

@Component
@Aspect
@Slf4j
public class OnceOnTheSameTimeAspect {

    @Autowired
    private CreateOperateOnceService createOperateOnceService;

    @Autowired
    private DistributeScheduleOnceService distributeScheduleOnceService;

    @Autowired
    private MessageIdempotenceOnceService messageIdempotenceOnceService;

    /**
     * execution(* xx.web.controller..*.create*(..))
     * execution(* set*(..))
     */
    @Pointcut("execution(* xx.web.controller..*.create*(..)) && @annotation(xx.annotation.OnceOnTheSameTime)")
    public void createCondition() {
    }

    /**
     * target方法如果只有一个参数,直接使用SpEL root对象取值即可;
     * target方法如果有多个参数,表达式中使用#args[0,1]来取值
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Around("createCondition()")
    public Object createAround(ProceedingJoinPoint joinPoint) throws Throwable {
        return createOperateOnceService.aroundInvoke(joinPoint);
    }


    @Pointcut("bean(scheduleConfig) && @annotation(xx.annotation.OnceOnTheSameTime)")
    public void scheduleCondition() {
    }

    @Around("scheduleCondition()")
    public Object scheduleAround(ProceedingJoinPoint joinPoint) throws Throwable {
        return distributeScheduleOnceService.aroundInvoke(joinPoint);
    }


    @Pointcut("execution(* xx.mq..*Consumer.*(..)) && @annotation(xx.annotation.OnceOnTheSameTime)")
    public void mqCondition() {
    }

    @Around("mqCondition()")
    protected Object mqAround(ProceedingJoinPoint joinPoint) throws Throwable {
        return messageIdempotenceOnceService.aroundInvoke(joinPoint);
    }
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
基于xxl-job改造,支持1.6jdk。改分布式任务调度特性如下: 1、简单:支持通过Web页面对任务进行CRUD操作,操作简单,一分钟上手; 2、动态:支持动态修改任务状态、暂停/恢复任务,以及终止运行中任务,即时生效; 3、调度中心HA(中心式):调度采用中心式设计,“调度中心”基于集群Quartz实现,可保证调度中心HA; 4、执行器HA(分布式):任务分布式执行,任务"执行器"支持集群部署,可保证任务执行HA; 5、任务Failover:执行器集群部署时,任务路由策略选择"故障转移"情况下调度失败时将会平滑切换执行器进行Failover; 6、一致性:“调度中心”通过DB锁保证集群分布式调度的一致性, 一次任务调度只会触发一次执行; 7、自定义任务参数:支持在线配置调度任务入参,即时生效; 8、调度线程池:调度系统多线程触发调度运行,确保调度精确执行,不被堵塞; 9、弹性扩容缩容:一旦有新执行器机器上线或者下线,下次调度时将会重新分配任务; 10、邮件报警:任务失败时支持邮件报警,支持配置多邮件地址群发报警邮件; 11、状态监控:支持实时监控任务进度; 12、Rolling执行日志:支持在线查看调度结果,并且支持以Rolling方式实时查看执行器输出的完整的执行日志; 13、GLUE:提供Web IDE,支持在线开发任务逻辑代码,动态发布,实时编译生效,省略部署上线的过程。支持30个版本的历史版本回溯。 14、数据加密:调度中心和执行器之间的通讯进行数据加密,提升调度信息安全性; 15、任务依赖:支持配置子任务依赖,当父任务执行结束且执行成功后将会主动触发一次子任务的执行, 多个子任务用逗号分隔;

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值