mybatis异步存储数据库

2020-04-17  本文已影响0人  风一样的存在

使用@Async异步任务,出现了一个问题:

异步异常
编写的代码如下:
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

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

/**
 * @Author: jack
 * @Description: 线程池配置
 * @Date: 2020/4/15 9:45
 * @Version: 1.0
 */
@EnableAsync
@Configuration
@Slf4j
public class ExecutorConfig {
    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(5);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(60);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}
    @Async
    @DataSource(DataSourceType.DataBaseType.OPINION)
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public int recordCompanyOpinion(List<CompanyOpinionDO> companyOpinionDOS,String companyId){
        List<CustomerOpinionDO> customerOpinionDOS = Lists.newArrayList();
        companyOpinionDOS.stream().forEach(companyOpinionDO -> {
            CustomerOpinionDO customerOpinionDO = new CustomerOpinionDO();
            customerOpinionDO.setCompanyId(companyId);
            customerOpinionDO.setCompanyOpinionId(companyOpinionDO.getId());
            customerOpinionDO.setRead(0);
            customerOpinionDO.setDeleted(0);
            customerOpinionDO.setCreateTime(new Date());
            customerOpinionDO.setUpdateTime(new Date());
            customerOpinionDOS.add(customerOpinionDO);
        });
        return customerOpinionMapper.insertList(customerOpinionDOS);
    }

问题的产生:由于使用异步导致,插入的操作没有及时返回结果

解决办法:去掉return,修改方法为void无返回值

上一篇 下一篇

猜你喜欢

热点阅读