(一)配置類注冊成Bean
package com.supconit.data.integration.service.threadPool;/**
* Created by dell on 2019/10/24.
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author:[email protected]
* @date: 2019-10-24 16:01
* @desc:線程池配置類
*/
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 設定核心線程數
executor.setCorePoolSize(5);
// 設定最大線程數
executor.setMaxPoolSize(10);
// 設定隊列容量
executor.setQueueCapacity(20);
// 設定線程活躍時間(秒)
executor.setKeepAliveSeconds(60);
// 設定預設線程名稱
executor.setThreadNamePrefix("hello-");
// 設定拒絕政策
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任務結束後再關閉線程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
(二 )Service層 , 有兩個異步方法,一個是新增日志,帶傳回值,一個是修改日志,不帶傳回值
public interface TaskLogService {
/**
* 插入任務運作日志
* @param taskId
* @param projeceSpaceId
* @return
*/
Future<String> insertTaskLog(Integer taskId, Integer projeceSpaceId);
/**
* 修改任務運作日志
* @param logId
* @param appendLog
* @return
*/
void updateTaskLog(Integer logId,String appendLog);
}
(三)ServiceImpl層,記得加上@Async注解,taskExecutor這個是剛才線程池生成的bean
@Service
public class TaskLogServiceImpl implements TaskLogService {
@Autowired
private TaskLogMapper taskLogMapper;
@Async("taskExecutor")
public Future<String> insertTaskLog(Integer taskId, Integer projeceSpaceId){
TaskLog taskLog = new TaskLog();
taskLog.setCreateTime(new Date());
taskLog.setProjectSpaceId(projeceSpaceId);
taskLog.setTaskId(taskId);
taskLogMapper.insertSelective(taskLog);
return new AsyncResult<String>(taskLog.getId().toString());
}
@Async("taskExecutor")
public void updateTaskLog(Integer logId, String appendLog){
TaskLog taskLog = taskLogMapper.selectByPrimaryKey( logId ) ;
if ( null != taskLog ){
String log = (taskLog.getLog() == null) ? "" : taskLog.getLog();
if (appendLog != null) {
log += "\n" + appendLog;
taskLog.setLog(log);
taskLog.setLastUpdateLog(new Date());
taskLogMapper.updateByPrimaryKeyWithBLOBs(taskLog);
}
}
}
}
(四)
想獲得異步的傳回值,如下
Future future = taskLogServiceImpl.insertTaskLog(taskId,projectSpaceId);
String taskLogId = future.get();