springboot定时任务线程池配置

首先定义的是异步线程池,需要再启动类添加注解

@EnableScheduling
@EnableAsync

package com.git.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class GitDemoApplication{

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

}

定义异步任务类

package com.git.demo.task;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    @Scheduled(cron = "0/1 * * * * ?")
    @Async
    public void scheduledTask1() throws Exception{
        int a=1/0;
        System.out.println(Thread.currentThread().getName()+"---scheduledTask1---"+System.currentTimeMillis());
        Thread.sleep(4000);
    }
    @Scheduled(cron = "0/1 * * * * ?")
    @Async("asyncTaskExecutor")
    public void scheduledTask2(){
        System.out.println(Thread.currentThread().getName()+"---scheduledTask2---"+System.currentTimeMillis());
    }
}

局部线程池

package com.git.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义局部线程池 使用时需要指定名称为asyncTaskExecutor
 */
@Component
public class AsyncTaskExecutorConfig {

    @Bean("asyncTaskExecutor")
    public AsyncTaskExecutor getAsyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //自定义线程池前缀
        executor.setThreadNamePrefix("defineAsyncTask-");
        //核心线程数
        executor.setCorePoolSize(2);
        //最大线程数
        executor.setMaxPoolSize(5);
        //队列大小
        executor.setQueueCapacity(50);
        //淘汰策略:CallerRunsPolicy:当线程池没有能力处理时直接在执行方法的调用线程中运行被拒绝的任务
        //          AbortPolicy:处理程序遭到拒绝时将抛出 RejectedExecutionException
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务调度完成在关闭线程池,保证所有的任务被正确处理
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //线程池关闭时等待其他任务的时间,不能无限等待,确保应用最后能被关闭。而不是无限期阻塞
        executor.setAwaitTerminationSeconds(60);
        //初始化线程池
        executor.initialize();
        return executor;
    }
}

全量线程池

package com.git.demo.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定义全局线程池
 */
@Component
public class AsyncGlobalConfig extends AsyncConfigurerSupport {

    @Value("${define.global.async.prefix}")
    private String threadName;
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix(threadName);
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(20);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    /**
     * 重写线程异常处理方法
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }
}

线程异常处理类

package com.git.demo.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import java.lang.reflect.Method;

/**
 * 处理线程异常
 */
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
        System.out.println("线程异常了");
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值