异步任务在实际业务中的使用

方法一:在类中创建一个线程池,开启异步任务

  1. 创建异步任务工厂
private class AsyncTaskFactory implements ThreadFactory {

        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "asyncTeddy-pool-" + threadNumber.getAndIncrement());
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }
  1. 创建线程池
private ExecutorService asyncExecutors = new ThreadPoolExecutor(32, 56,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(1024),
            new AsyncTaskFactory(),
            new ThreadPoolExecutor.DiscardPolicy());
  1. 创建异步任务类
private class AsyncTask implements Runnable {

        private String hashKey;

        private String sortKey;

        private int ttl;

        private PegasusClientInterface pegasusClientInterface;
        AsyncTask(String hashKey, String sortKey, int ttl, PegasusClientInterface pegasusClientInterface) {
            this.hashKey = hashKey;
            this.sortKey = sortKey;
            this.ttl = ttl;
            this.pegasusClientInterface = pegasusClientInterface;
        }

        @Override
        public void run() {
            try {
                pegasusClientInterface.incr(richMsgLimitTable, hashKey.getBytes(), sortKey.getBytes(), 1, ttl);
            } catch (PException e) {
                log.error("incr oaId limit failed. hashKey is {}, sortKey is {}", hashKey, sortKey, e);
            }
        }
    }

方法二:创建一个线程池类,在方法上添加注解

  1. 创建线程池类
@Configuration
@EnableAsync
public class AsyncThreadPoolConfig {

    public static final String FIND_INFO = "find-info";

    @Bean(value = FIND_INFO)
    public ThreadPoolTaskExecutor findInfo() {
        return getTaskExecutor(FIND_INFO + "-");
    }

    private ThreadPoolTaskExecutor getTaskExecutor(String prefix) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数,它是可以同时被执行的线程数量
        executor.setCorePoolSize(10);
        // 设置最大线程数,缓冲队列满了之后会申请超过核心线程数的线程
        executor.setMaxPoolSize(20);
        // 设置缓冲队列容量,在执行任务之前用于保存任务
        executor.setQueueCapacity(60);
        // 设置线程生存时间(秒),当超过了核心线程出之外的线程在生存时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 设置线程名称前缀
        executor.setThreadNamePrefix(prefix);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 最多等待60s
        executor.setAwaitTerminationSeconds(60);
        // 初始化
        executor.initialize();
        return executor;
    }
}
  1. 创建异步任务结果类
public class AsyncResult<T> implements Future<T> {

    private T result;

    public AsyncResult(T result) {
        this.result = result;
    }

    /**
     * 异步任务不支持取消操作,直接返回false
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return
     */
    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    /**
     * 异步任务不支持取消操作,直接返回false
     * @return
     */
    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return false;
    }

    /**
     * 直接返回异步执行的结果
     * @return
     */
    @Override
    public T get() throws InterruptedException, ExecutionException {
        return result;
    }

    /**
     * 直接返回异步执行的结果,不等待超时时间
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     * @throws TimeoutException
     */
    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return result;
    }
}
  1. 方法上添加注解
@Async(value = AsyncThreadPoolConfig.FIND_INFO)
    public Future<Info> find(String info) {
       
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值