天天看点

springboot 结合线程池 实现异步调用并获取返回结果

(一)配置类注册成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();

继续阅读