1.自定义多线程配置
#线程池配置
threadpool:
core-pool-size: 10
max-pool-size: 20
queue-capacity: 10
keep-alive-seconds: 60
2.配置类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步线程池配置
*/
@Slf4j
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Value("${threadpool.core-pool-size}")
private int corePoolSize;
@Value("${threadpool.max-pool-size}")
private int maxPoolSize;
@Value("${threadpool.queue-capacity}")
private int queueCapacity;
@Value("${threadpool.keep-alive-seconds}")
private int keepAliveSeconds;
@Bean(name = "taskExecutor")
@Primary
public Executor taskExecutor() {
log.info("start executor -->");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(corePoolSize);
//设置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//设置队列大小
executor.setQueueCapacity(queueCapacity);
//配置线程池的前缀
executor.setThreadNamePrefix("async-taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//设置空闲时间
executor.setKeepAliveSeconds(keepAliveSeconds);
//进行加载
executor.initialize();
return executor;
}
}
3.多线程调用
//如果在同一个类中调用异步方法,需要手动的注入Bean,所以需要自调用懒加载一下
@Autowired
@Lazy
private JkYjkMbMemberTagServiceImpl jkYjkMbMemberTagServiceImpl;
/**
* 异步同步会员标签
* @param list
*/
@Async("taskExecutor")
public void updateAccountMemberLabel(List<JkYjkMbMemberTagEntity> list) {
for (JkYjkMbMemberTagEntity entity : list) {
AccountMemberLabelEntity labelEntity = BeanUtil.copyProperties(entity, AccountMemberLabelEntity.class);
accountMemberLabelService.addOrUpdate(labelEntity);
}
}
@Async失效情况
1.注解@Async的方法不是public方法
2.注解@Async的返回值只能为void或Future
3.注解@Async方法使用static修饰也会失效
4.spring无法扫描到异步类,没加注解@Async或@EnableAsync注解
5.调用方与被调用方不能在同一个类
6.类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
7.在Async方法上标注@Transactional是没用的.但在Async方法调用的方法上标注@Transcational是有效的