异步任务模板

这儿都是满满的干货!

从来不多说废话,直接上代码 ,拿来皆可用的那种 


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author x y
 * @description 线程工具
 * @date 2022-03-23 11:32
 */
public class Threads {

    protected final static Logger log = LoggerFactory.getLogger(Threads.class);

    /**
     * 停止线程池
     * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
     * 如果仍人超時,則強制退出.
     * 另对在shutdown时线程本身被调用中断做了处理.
     */
    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                        log.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @author x y
 * @description 确保退出时能关闭后台线程
 * @date 2022-03-23 11:30
 */
@Component
public class ShutdownManager {
    protected final static Logger log = LoggerFactory.getLogger(ShutdownManager.class);

    @PreDestroy
    public void destroy() {
        shutdownAsyncManager();
    }

    /**
     * 停止异步执行任务
     */
    private void shutdownAsyncManager() {
        try {
            log.info("关闭后台任务任务线程池");
            AsyncManager.getInstance().shutdown();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}


import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author x y
 * @description 异步任务管理器
 * @date 2022-03-23 11:23
 */
public class AsyncManager {
    /**
     * 核心线程数大小
     **/
    private int corePoolSize = 8;

    /**
     * 操作延迟10毫秒
     **/
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     **/
    private ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(corePoolSize,
            new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            //线程执行之后
            super.afterExecute(r, t);
        }
    };

    // 单例模式
    private AsyncManager() {

    }

    private static AsyncManager asyncManager = new AsyncManager();

    public static AsyncManager getInstance() {
        return asyncManager;
    }

    /**
     * 异步执行任务 10毫秒后执行
     *
     * @param runnable 任务
     **/
    public void executor(Runnable runnable) {
        executor.schedule(runnable, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     **/
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
    }
}


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Queues;
import com.yw.processplan.core.constant.StompMappingConstant;
import com.yw.processplan.core.utlis.StringUtils;
import com.yw.processplan.core.websocket.StompMessagePusher;
import com.yw.processplan.module.power.dao.MessageMapper;
import com.yw.processplan.module.power.model.Performer;
import com.yw.processplan.module.power.model.entity.SendMessageEntity;
import com.yw.processplan.module.process.model.dto.WebSocketAccountDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author x y
 * @description 
 * @date 2022-03-11 11:38
 */
@Component
public class SendMessageActuator {
    protected static final Logger LOGGER = LoggerFactory.getLogger(SendMessageActuator.class);

    @Autowired
    private TaskScheduler taskScheduler;


    /**
     * 任务队列
     **/
    private static LinkedBlockingQueue<WebSocketAccountDTO> ACCOUNT_BLOCK_QUEUE = Queues.newLinkedBlockingQueue(200);

    /**
     * 异步执行线程
     **/
    private static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MICROSECONDS,
            new LinkedBlockingQueue<>(200), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());


    @PostConstruct
    public void doDispose() {
        taskScheduler.scheduleAtFixedRate(() -> {
            WebSocketAccountDTO accountDTO = ACCOUNT_BLOCK_QUEUE.poll();
            if (accountDTO == null) {
                return;
            }
            CompletableFuture<?> future = CompletableFuture.runAsync(() -> {
                doProcess(accountDTO); // 异步任务具体处理
            }, POOL_EXECUTOR);
            future.thenAccept((U) -> {
                LOGGER.info("success...............");
            });
        }, 1000);
    }

    private void doProcess(WebSocketAccountDTO accountDTO) {
        
    }

    public static void offer(WebSocketAccountDTO dto) {
        if (ACCOUNT_BLOCK_QUEUE.contains(dto)) {
            return;
        }
        ACCOUNT_BLOCK_QUEUE.offer(dto);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值