Solon v3.0.2

使用分布式任务

</> markdown

生态 / Solon Cloud Job [传送]

1、情况简介

使用分布式任务(目前适配有:local, water, xxl-job, quartz)

2、简单示例

//注解模式 - Hander 风格(也可以用:Bean method 风格)
//water 支持直接注册进去,并附带cron7x,description(注册后亦可调)
@CloudJob(name="JobHandlerDemo1", cron7x = "0 30 0 * * ?", description="示例") 
public class JobHandlerDemo1 implements CloudJobHandler {
    @Override
    public void handle(Context ctx) throws Throwable {
        //任务处理
    }
}

//手动模式
CloudClient.job().register("JobHandlerDemo3","",c->{
    //任务处理 
});

拦截任务处理(记录消耗时间、日志等)

@Component
public class JobInterceptorImpl implements CloudJobInterceptor {
    static Logger log = LoggerFactory.getLogger(BaseJobInterceptor.class);

    @Override
    public void doIntercept(Job job, CloudJobHandler handler) throws Throwable {
        TagsMDC.tag0("job");
        TagsMDC.tag1(job.getName());

        Timecount timecount = new Timecount().start();
        long timespan = 0;

        try {
            handler.handle(job.getContext());
            timespan = timecount.stop().milliseconds();

            log.info("Job execution succeeded @{}ms", timespan);
        } catch (Throwable e) {
            timespan = timecount.stop().milliseconds();

            log.error("Job execution error @{}ms: {}", timespan, e);
            throw e;
        } finally {
            if (timespan > 0) {
                CloudClient.metric().addMeter(Solon.cfg().appName(), "job", job.getName(), timespan);
            }
        }
    }
}

代码演示:

https://gitee.com/noear/solon-examples/tree/main/9.Solon-Cloud