技术分享

长耗时任务的善后处理

2019-07-29  本文已影响0人  固安李庆海

背景

在开发中有时会遇到长耗时的任务,我们又不想傻傻的等待任务的执行完成后才可能进行其他的操作。这时我们首先想到的是使用多线程进行异步处理,那么如何才能知道任务的执行状态呢,如执行了多长时间,执行的结果是成功了还是失败了。

此处提到的长耗时任务是指本身已经经过优化了不能在拆分的情况,如果任务还可以在拆分请先拆分,不要为难你自己。

如果项目中只是一次性或者很少量是这种情况,怎么着也能忍了;此处面对的是大量的,并且是需要经常处理的情况。

如果是定时任务或者在控制台执行的,就忍着吧,我们总是对自己很残忍,对他人很友善的。

总之此处要面对的就是项目中有大量的长耗时任务,需要在页面上点击某个按钮后立即返回,还要知道任务执行的情况。

解决方法

办法总比问题多,总是有解决的方法的。我用到的技术主要是自定义注解、AOP、@Async。不太了解的请自行扫盲,此处不做展开。

具体代码

自定义注解

import java.lang.annotation.*;

/**
 * 后续操作
 * @author 李庆海
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Aftermath {

    /**
     * 运行结果保存的路径
     * 相对路径是指相对prefix返回值而言
     * @return
     */
    String path() default "";

    /**
     * 运行结果保存的根路径
     * @return
     */
    String prefix() default "/devops/ydhxg/";
}

善后处理拦截器

import cn.com.yd.cygp4.webinterface.YuandayunHelper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;

/**
 * 后续操作拦截器
 *
 * @author 李庆海
 */
@Aspect
@Component
@Slf4j
public class AftermathInterceptor {

    @Pointcut("@annotation(cn.com.yd.cygp4.webinterface.annotations.Aftermath)")
    public void aspect() {

    }

    @Around(value = "aspect()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        log.debug("进入事后处理");
        Object reO = null;
        // 返回目标对象
        Object target = point.getTarget();
        String targetName = target.getClass().getName();
        // 返回当前连接点签名
        String methodName = point.getSignature().getName();
        // 获得参数列表
        Object[] arguments = point.getArgs();
        Class<?> targetClass = Class.forName(targetName);
        // 获取参数类型数组
        Class<?>[] argTypes = ReflectUtils.getClasses(arguments);
        // 获取目标method,考虑方法的重载等问题
        Method method = targetClass.getDeclaredMethod(methodName, argTypes);
        // 获取目标method上的注解
        Aftermath annotation = method.getAnnotation(Aftermath.class);
        if (null != annotation) {
            String status = null;
            StopWatch clock = new StopWatch();
            //计时开始
            clock.start();
            try {
                reO = point.proceed();
                status = "成功";
            }catch(Exception e){
                status = "失败";
            }finally {
                clock.stop();
                JSONObject json = new JSONObject();
                //执行状态
                json.put("status",status);
                // 花费的时间
                json.put("take",clock.getTotalTimeSeconds());
                String path = annotation.path();
                if(null == path || "".equals(path)){
                    path = targetName+"/"+methodName;
                }
                path = annotation.prefix()+path;
                System.out.println("path:"+path);
                System.out.println(json);
                YuandayunHelper.delete(path);
                YuandayunHelper.add(path,json);
            }
        } else {
            reO = point.proceed();
        }
        log.debug("退出事后处理");
        return reO;
    }
}

异步执行

开启异步执行

/**
 * Springboot 程序入口
 *
 * @author 李庆海
 */
@SpringBootApplication
@EnableAsync
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}

在目标方法上添加@Async

@Async
public Object chushihuagupiaogainian() {
    //do something;
    return something;
}

长耗时异步执行示例

import cn.com.yd.cygp4.webinterface.annotations.Aftermath;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 龙虎榜手动管理Controller
 *
 * @author 李庆海
 */
@RestController
@RequestMapping("${admin-url}")
@Api(tags = "后台管理")
public class AdminController {

    /**
     * 初始化
     *
     * @return
     */
    @GetMapping("/init")
    @ApiOperation("后台管理 > 数据初始化")
    @Aftermath
    @Async
    public Object init() {
        //此处耗时5m;
        return something;
    }

最后

这些代码都是从实际开发中提炼出来的,与业务具有一定的绑定。为了跳出局限使其具有通用性,可以进行一些优化,比如将写入操作抽象一个接口如IWrite,定义一个方法write(String path,String content),然后根据场景进行实现即可达到通用的目的。关于执行结果的获取就更好办了,可以是监听、可以是轮询。

上一篇 下一篇

猜你喜欢

热点阅读