============= 后端_线程池化 ============= 1 在辅助线程中更新数据库 ... public class ArticleServiceImpl implements ArticleService { ... @Override public Result details(Long articleId) { ... // 每次显示文章详情,文章阅读数加一 updateArticleViewCount(articleMapper, article.getId(), article.getViewCount()); ... } ... } - 在这里更新t_article表的view_count字段,势必会延长业务响应时间 - 更好的处理方法是将更新数据库表的操作放到辅助线程中,并立即返回 - 每次派发都要创建全新的辅助线程同样会带来开销,借助池化提高性能 -----------------> 主线程 派|发 _______|________ | | | | v | | ----------> 辅 | | ----------> 助 | 线程池 | ----------> 线 | | ----------> 程 | |________________| 2 线程池配置类 /ysdblog-api/src/main/java/com/weihome/ysdblog/config/ThreadPoolConfig.java: @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("YSDBLOG"); // 所有任务结束后关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); // 初始化 executor.initialize(); return executor; } } 3 线程服务类 /ysdblog-api/src/main/java/com/weihome/ysdblog/service/ThreadService.java: @Component public class ThreadService { /** * 更新文章阅读数 * 此方法在taskExecutor线程池中执行 */ @Async("taskExecutor") public void updateArticleViewCount( ArticleMapper articleMapper, long id, int viewCount) { /* try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } */ Article article = new Article(); article.setViewCount(viewCount + 1); LambdaUpdateWrapper
updateWrapper = new LambdaUpdateWrapper<>(); updateWrapper.eq(Article::getId, id); updateWrapper.eq(Article::getViewCount, viewCount); // 只更新非空属性对应的字段 articleMapper.update(article, updateWrapper); } } 4 文章服务实现 /ysdblog-api/src/main/java/com/weihome/ysdblog/service/impl/ArticleServiceImpl.java: ... public class ArticleServiceImpl implements ArticleService { ... @Autowired private ThreadService threadService; ... @Override public Result details(Long articleId) { ... // 每次显示文章详情,文章阅读数加一 threadService.updateArticleViewCount(articleMapper, article.getId(), article.getViewCount()); ... } ... } 5 运行测试 Postman GET localhost:8888/article/details/1 ---------------------------------------- { "success": true, "code": 200, "msg": "success", "data": { "id": 1, "commentCount": 1, "createDate": "2022-01-01 13:22:59", "summary": "summary_a", "title": "title_a", "viewCount": 2, "weight": 1, "author": "nickname_a", "content": { "content": "content_a" }, "category": { "id": 1, "avatar": "category_a.png", "categoryName": "category_a" }, "tags": [ { "id": 1, "tagName": "tag_a" } ] } } 检查数据库中t_article表特定文章记录的view_count字段。 增加睡眠延时检验线程池效果。