Spring Boot中线程池使用

news/2024/10/8 20:45:57 标签: spring boot, 后端, java

说明:在一些场景,如导入数据,批量插入数据库,使用常规方法,需要等待较长时间,而使用线程池可以提高效率。本文介绍如何在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;

    @Autowired
    private UserService userService;

    @Autowired
    private 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")
    @Override
    public 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.niftyadmin.cn/n/5694769.html

相关文章

云微客AI直播矩阵,让小白轻松上手的必备直播利器

现在直播带货都已经杀疯了&#xff0c;在新趋势下&#xff0c;AI智能直播应运而生。AI智能直播相较于传统直播&#xff0c;直播模式对于场地的要求和人员的要求都相对较低&#xff0c;大大降低了我们的试错成本&#xff0c;同时直播矩阵系统也为企业和个人带来了低成本、高效率…

VBA经典应用69例应用6:利用VBA进行格式化的设置

《VBA经典应用69例》&#xff08;版权10178981&#xff09;&#xff0c;是我推出的第九套教程&#xff0c;教程是专门针对初级、中级学员在学习VBA过程中可能遇到的案例展开&#xff0c;这套教程案例众多&#xff0c;紧贴“实战”&#xff0c;并做“战术总结”&#xff0c;以便…

pytorch中的TensorDataset和DataLoader

TensorDataset 详解 TensorDataset 主要用于将多个 Tensor 组合在一起&#xff0c;方便对数据进行统一处理。它可以用于简单地将特征和标签配对&#xff0c;也可以将多个特征张量组合在一起。 1. 将特征和标签组合 假设我们有一组图像数据&#xff08;特征&#xff09;和对应…

【RTCP】Interarrival Jitter: 到达间隔抖动的举例说明

Interarrival Jitter: 32位,表示接收到的数据包间隔的抖动,用于评估网络延迟变化情况。给出一些具体实例,帮助理解“Interarrival Jitter”(到达间隔抖动)是指接收到连续数据包之间时间间隔的变化情况,这个指标用于评估网络的稳定性和延迟的波动情况。在RTP中,接收端会计…

【大数据】在线分析、近线分析与离线分析

文章目录 1. 在线分析&#xff08;Online Analytics&#xff09;定义特点应用场景技术栈 2. 近线分析&#xff08;Nearline Analytics&#xff09;定义特点应用场景技术栈 3. 离线分析&#xff08;Offline Analytics&#xff09;定义特点应用场景技术栈 总结 在线分析&#xff…

vue2与vue3知识点

1.vue2&#xff08;optionsAPI&#xff09;选项式API 2.vue3&#xff08;composition API&#xff09;响应式API vue3 setup 中this是未定义&#xff08;undefined&#xff09;vue3中已经开始弱化this vue2通过this可以拿到vue3setup定义得值和方法 setup语法糖 ref > …

笔记整理—linux进程部分(8)线程与进程

前面用了高级IO去实现鼠标和键盘的读取&#xff0c;也说过要用多进程方式进行该操作&#xff1a; int mian(void) {int ret-1;int fd-1;char bug[100]{0};retfork();if(0ret){//子进程&#xff0c;读鼠标}if(0<ret){//父进程&#xff0c;读键盘}else{perror("fork&quo…

浅色系统B端管理系统标配,现在也卷起了可视化,挡不住呀

在 B 端管理系统的领域中&#xff0c;浅色系统一直以来都是标配之选。其简洁、清新的外观&#xff0c;给人以专业、高效的视觉感受。如今&#xff0c;浅色系统更是卷入了可视化的浪潮&#xff0c;这一趋势势不可挡。 浅色系统的优势在于它能够营造出一种舒适的视觉环境&#x…