springboot 异步任务实践

1.自定义线程池

@EnableAsync
@Component
public class TaskPoolConfig {

    /**
     * 自定义线程池
     */
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        // 返回可用处理器的Java虚拟机的数量 12
        int i = Runtime.getRuntime().availableProcessors();
        System.out.println("系统最大线程数  : " + i);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(16);
        // 最大线程数
        executor.setMaxPoolSize(20);
        // 配置队列容量,默认值为Integer.MAX_VALUE
        executor.setQueueCapacity(99999);
        // 活跃时间
        executor.setKeepAliveSeconds(60);
        // 线程名字前缀
        executor.setThreadNamePrefix("asyncServiceExecutor -");
        // 设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
        executor.setAwaitTerminationSeconds(60);
        // 等待所有的任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }

2. 创建异步接口

public interface AsyncService {
    void checkSignStatus(String id, int type) throws  Exception;
}
@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {

    @Async("taskExecutor")
    @Override
    public void checkSignStatus(String contractId, int type) throws Exception {
        String name = Thread.currentThread().getName();
        log.info("currentThreadName={}",name);
        //业务逻辑

    }
}

3.直接使用接口


@RestController
@Slf4j
@RequestMapping("/test")
public class TestController {

    @Autowired
    AsyncService asyncService;
    
    @RequestMapping(value = "/testAsync",method = RequestMethod.GET)
    public Result<Object> testAsync() throws Exception {
        asyncService.checkSignStatus("test123",12);
        System.out.println("currentThreadName:");
        System.out.println(Thread.currentThread().getName());
        return Result.success();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值