四、使用案例
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5, new ThreadFactoryBuilder().setDaemon(false).setNamePrefix("execApiCache").build()); @Override @Transactional(rollbackFor = Exception.class) public ResultVO addApi(Api api, List<Header> headerList, List<Request> requestList, Response response, List<Script> scriptList, List<RespCodeMapping> respCodeMappingList) { // 数据库代码... // 异步代码 TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { log.warn("afterCommit..."); executorService.execute(() -> { // 异步业务 execApiCache(api); }); }}); return ResultUtil.buildSucc(); }
Ps:setDaemon(false) 注意这里守护线程标记必须设置为 false,否则主线程执行完,异步线程没执行完的话,异步线程会马上被中断、关闭,所以这里不能设置成守护(用户)线程。