原csdn地址https://blog.cs|

蜗牛使劲冲

园龄:7年6个月粉丝:3关注:10

java增加注解实现异步执行任务

1.首先启动类增加注解

@EnableAsync

2.增加config

package com.xxx.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("AsyncExecutor-");
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            throwable.printStackTrace();
            // 可以在这里记录异常信息
        };
    }
}

 

 

3.你的service增加注解

    @Async
    @Override
    public void createPacket(ActivityPacketSettingCreateAO req) {
        // 执行任务代码
    }

完事

本文作者:蜗牛使劲冲

本文链接:https://www.cnblogs.com/warrenwt/p/18385002

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   蜗牛使劲冲  阅读(44)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起