在springboot项目中一个方法如果被@Sync
注解修饰,表示它是一个异步操作的方法。前提需要自己通过@EnableAsync
开启。另外如果自己没有配置线程池,那么Springboot则使用默认好的线程池SimpleAsyncTaskExecutor
,效果并不是很好,通过需要自己手动配置。
配置类ThreadPoolConfig
如下:
@Configuration
@EnableAsync //开启线程池 异步操作
public class ThreadPoolConfig {
@Bean("taskExecutor") //指定注入容器中Bean的名称
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(5);
// 设置最大线程数
executor.setMaxPoolSize(20);
//配置队列大小
executor.setQueueCapacity(Integer.MAX_VALUE);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称
executor.setThreadNamePrefix("码神之路博客项目");
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
//执行初始化
executor.initialize();
return executor;
}
}
开启异步操作的方法如下:
@Component
public class ThreadService {
//指定配置好的多线程
@Async("taskExecutor") //执行多线程异步任务
public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
//使用线程池,不会影响原有的操作
int viewCounts = article.getViewCounts();
Article articleUpdate =new Article();
articleUpdate.setViewCounts(viewCounts+1);
LambdaUpdateWrapper<Article> updateWrapper=new LambdaUpdateWrapper<>();
updateWrapper.eq(Article::getId,article.getId());
//设置一个 为了在多线程的环境下 线程安全
updateWrapper.eq(Article::getViewCounts,article.getViewCounts());
//update article set view_count=100 where view_count=99 and id=11
articleMapper.update(articleUpdate,updateWrapper);
try {
TimeUnit.SECONDS.sleep(5);
System.out.println("更新完成了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}