Spring Boot中线程池使用

devtools/2024/10/9 1:48:20/

说明:在一些场景,如导入数据,批量插入数据库,使用常规方法,需要等待较长时间,而使用线程池可以提高效率。本文介绍如何在Spring Boot中使用线程池来批量插入数据。

搭建环境

首先,创建一个Spring Boot项目,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version><relativePath/></parent><groupId>com.hezy</groupId><artifactId>thread_pool_demo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.8</version></dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.6</version></dependency></dependencies>
</project>

写一个插入数据的Mapper方法

java">import com.hezy.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;@Mapper
public interface UserMapper {@Insert("insert into i_users (username, password) values (#{user.username}, #{user.password})")void insert(@Param("user") User user);
}

写一个接口,用来插入20万条记录,如下:

java">import com.hezy.pojo.User;
import com.hezy.service.AsyncService;
import com.hezy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.ArrayList;@RestController
@RequestMapping("user")
public class UserController {/*** 总记录数*/private final static int SIZE = 40 * 10000;@Autowiredprivate UserService userService;@Autowiredprivate AsyncService asyncService;@GetMapping("insert1")public void insert1() {ArrayList<User> list = new ArrayList<>(SIZE);for (int i = 0; i < SIZE; i++) {User user = new User();user.setUsername("user" + i);user.setPassword("password" + i);list.add(user);}long startTime = System.currentTimeMillis();// 批量插入for (User user : list) {userService.insert(user);}long endTime = System.currentTimeMillis();System.out.println("不用线程池===插入40万条记录耗时:" + ((endTime - startTime) / 1000) + "s");}
}

启动项目,测试一下,看要多长时间……11分钟

在这里插入图片描述

使用线程池

Spring Boot有自动注入的线程池(threadPoolTaskExecutor),可以手动设置一些属性,为我们所用。

java">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;@Configuration
@EnableAsync
public class ThreadPoolConfig {@Bean(name = "threadPoolTaskExecutor")public Executor threadPoolTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(20);executor.setMaxPoolSize(40);executor.setQueueCapacity(500);executor.setKeepAliveSeconds(60);executor.setThreadNamePrefix("hezy-");executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());executor.initialize();return executor;}
}

使用线程池来完成上面插入数据的操作,如下:

java">    @GetMapping("insert2")public void insert2() {ArrayList<User> list = new ArrayList<>(SIZE);for (int i = 0; i < SIZE; i++) {User user = new User();user.setUsername("user" + i);user.setPassword("password" + i);list.add(user);}// 将数据分成4000批,每批插入100条List<List<User>> batchList = new ArrayList<>();for (int i = 0; i < list.size(); i += 100) {batchList.add(list.subList(i, i + 100));}long startTime = System.currentTimeMillis();CountDownLatch countDownLatch = new CountDownLatch(batchList.size());// 线程池分批插入for (List<User> batch : batchList) {asyncService.executeAsync(batch, userService, countDownLatch);}try {countDownLatch.await();} catch (InterruptedException e) {throw new RuntimeException(e);}long endTime = System.currentTimeMillis();System.out.println("使用线程池===插入40万条记录耗时:" + ((endTime - startTime) / 1000) + "s");}

AsyncService实现类

java">import com.hezy.pojo.User;
import com.hezy.service.AsyncService;
import com.hezy.service.UserService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.concurrent.CountDownLatch;@Service
public class AsyncServiceImpl implements AsyncService {@Async("threadPoolTaskExecutor")@Overridepublic void executeAsync(List<User> batch, UserService userService, CountDownLatch countDownLatch) {try {for (User user : batch) {userService.insert(user);}} finally {countDownLatch.countDown();}}
}

启动,测试,速度提升很明显。如果再改造一下insert()方法,一次插入多条数据,肯定还能更快。

在这里插入图片描述

总结

本文介绍如何使用Spring Boot装配的线程池Bean,完成大数据量的批量插入操作,提高程序执行效率。

实例完整代码:https://github.com/HeZhongYing/thread_pool_demo

参考B站UP主(孟哥说Java)视频:https://www.bilibili.com/video/BV18r421F7CQ


http://www.ppmy.cn/devtools/123133.html

相关文章

提升开机速度:有效管理Windows电脑自启动项,打开、关闭自启动项教程分享

日常使用Windows电脑时&#xff0c;总会需要下载各种各样的办公软件。部分软件会默认开机自启功能&#xff0c;开机启动项是指那些在电脑启动时自动运行的程序和服务。电脑开机自启太多的情况下会导致电脑卡顿&#xff0c;开机慢&#xff0c;运行不流畅的情况出现&#xff0c;而…

Docker 安装 Citus 单节点集群:全面指南与详细操作

Docker 安装 Citus 单节点集群&#xff1a;全面指南与详细操作 文章目录 Docker 安装 Citus 单节点集群&#xff1a;全面指南与详细操作一 服务器资源二 部署图三 安装部署1 创建网络2 运行脚本1&#xff09;docker-compose.cituscd1.yml2&#xff09;docker-compose.cituswk1.…

PAT甲级-1122 Hamiltonian Cycle

题目 题目大意 给定一个图和几组顶点&#xff0c;判断每组顶点是否能构成一个哈密顿回路。 知识点 哈密顿回路满足几点要求&#xff1a;构成一个封闭环&#xff0c;并且经过所有顶点&#xff0c;每个顶点经过一次。 即满足第一个顶点值和最后一个顶点值相等&#xff1b;只有…

【S32K3 RTD MCAL 篇1】 K344 KEY 控制 EMIOS PWM

【S32K3 RTD MCAL 篇1】 K344 KEY 控制 EMIOS PWM 一&#xff0c;文档简介二&#xff0c; 功能实现2.1 软硬件平台2.2 软件控制流程2.3 资源分配概览2.4 EB 配置2.4.1 Dio module2.4.2 Icu module2.4.4 Mcu module2.4.5 Platform module2.4.6 Port module2.4.7 Pwm module 2.5 …

与ZoomEye功能类似的搜索引擎还有哪些?(渗透课作业)

与ZoomEye功能类似的搜索引擎有&#xff1a; Shodan&#xff1a;被誉为“物联网的搜索引擎”&#xff0c;专注于扫描和索引连接到互联网的各种设备&#xff0c;如智能家居设备、工业控制系统、摄像头、数据库等。它提供全球互联网设备的可视化视图&#xff0c;帮助用户了解网络…

如何实现 C/C++ 与 Python 的通信?

在现代编程中&#xff0c;C/C与Python的通信已经成为一种趋势&#xff0c;尤其是在需要高性能和灵活性的场景中。本文将深入探讨如何实现这两者之间的互通&#xff0c;包括基础和高级方法&#xff0c;帮助大家在混合编程中游刃有余。 C/C 调用 Python&#xff08;基础篇&#…

Linux shell编程学习笔记86:sensors命令——硬件体温计

0 引言 同事们使用的Windows系统电脑&#xff0c;经常莫名其妙地装上了鲁大师&#xff0c;鲁大师的一项功能是显示系统cpu等硬件的温度。 在Linux系统中&#xff0c;sensors命令可以提供类似的功能。 1 sensors命令 的安装和配置 1.1 sensors命令 的安装 要使用sensors命…

sqli-labs靶场less-9和less-10

sqli-labs靶场less-9 本文只展示如何利用dnslog注入通过本关&#xff0c;注入原理可以参考我另外一篇文章 DSNlog注入原理 1、确定闭合方式 http://192.168.140.130/sq/Less-9/?id1 发现id的值不论为任何值&#xff0c;页面回显都是一致的You are in… 判断不存在布尔注入…