项目场景:
今天在做个人博客项目时,当用户浏览文章时,需要对文章的浏览量进行更新浏览数量,刚开始我的想法是在得到文章内容后对浏览次数进行增加,但是这样势必会导致查询文章内容这个接口的执行时间会增强,通过查询有关知识,以及结合之前学的线程池,我想到了使用线程池对阅读次数进行更新,利用线程池可以不会影响主线程所执行的内容。
解决方法:
首先我们要在我们的项目中导入线程池的配置文件,将这个类交给我们的spring管理,开启多线程注解,在配置文件设置核心线程数、最大线程数、线程的活跃时间等进行配置。代码如下:
@Configuration @EnableAsync public class ThreadPoolConfig { @Bean("taskExecutor") 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 ThreadLoaclservice { @Async("taskExecutor") public void updateviewcount(ArticleMapper articleMapper, Article article) { Article articleUpdate = new Article(); articleUpdate.setViewCounts(article.getViewCounts() + 1); LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(Article::getId,article.getId()); queryWrapper.eq(Article::getViewCounts,article.getViewCounts()); articleMapper.update(articleUpdate,queryWrapper); try { //睡眠3秒 证明不会影响主线程的使用 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
然后就是线程池的使用了,如上段代码, 可以在里面的updateviewcount方法上添加 @Async注解,使用线程池,在方法里面写需要更新用户浏览次数的业务,最后可以调用Thread.sleep()方法进行验证是否影响主线程的使用,以上就是使用线程池进行更新阅读次数的方法。