Java实现10W+数据场景详细教程

在很多面试官面前都会问道如果添加10W条数据,甚至百万条数据你该怎么写?
接下来请我一起操作,带你看一下
在看代码之前需要使用SpringBoot+MyBatis-Plus实现后端

1.yml

#配置数据源的属性
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/interview?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC&rewriteBatchedStatements=true&autoReconnectForPools=true
      username: root
      password: root
      max-active: 20
      max-wait: 5000
      initial-size: 1
      filters: stat,log4j,wall
      validationQuery: SELECT 'x'   #验证连接
      enable: true
      #监控配置
      stat-view-servlet:
        enabled: true
        login-username: root
        login-password: root
        allow:
        deny:
        url-pattern: /druid/*
  #thymeleaf的配置
  thymeleaf:
    cache: false
    enabled: true

  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
#配置mybatisplus
mybatis-plus:
  mapper-locations:
    - classpath:mapper/*/*Mapper.xml
  global-config:
    db-config:
      id-type: auto
    banner: true
server:
  port: 8090

2.controller层

@RestController
@RequestMapping("exam")
public class UserController {
    
    @ApiOperation("实现10W+处理场景")
    @RequestMapping("handle")
    public void handle() throws InterruptedException {
        this.sysUserService.handle();
    }
}

3.service

public interface UserService extends IService<User> {

    void handle() throws InterruptedException;

}

4.impl


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rst.entity.User;
import com.rst.mapper.UserMapper;
import com.rst.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public void handle() throws InterruptedException {
        // 获取可用的处理器核心数
        int nThreads = Runtime.getRuntime().availableProcessors();
        // 创建一个固定大小的线程池,线程数量为核心数的两倍
        ExecutorService executor = Executors.newFixedThreadPool(nThreads * 2);
        int batchSize = 10000; // 每个批次插入的数据量
        int totalSize = 100000; // 总数据量
        // 初始化一个包含批次大小的用户列表
        List<User> userList = new ArrayList<>(batchSize);
        // 记录开始时间,用于计算插入操作的总耗时
        long time = System.currentTimeMillis();
        // 循环生成总数据量的用户对象并添加到用户列表中
        for (int i = 0; i < totalSize; i++) {
            // 创建一个新的用户对象并设置用户名
            User user = new User();
            user.setSuName("User" + i);
            userList.add(user);

            // 当用户列表的大小达到批次大小时
            if (userList.size() == batchSize) {
                // 创建一个用户列表的副本作为批次
                List<User> batch = new ArrayList<>(userList);
                // 异步提交批次进行保存
                CompletableFuture.runAsync(() -> this.saveBatch(batch), executor);
                // 清空用户列表以便开始新的批次
                userList.clear();
            }
        }
        // 如果用户列表中还有未处理的数据(不满一个批次)
        if (!userList.isEmpty()) {
            // 创建一个用户列表的副本作为最后的批次
            List<User> batch = new ArrayList<>(userList);
            // 异步提交最后的批次进行保存
            executor.submit(() -> CompletableFuture.runAsync(() -> this.saveBatch(batch), executor));
        }
        // 关闭线程池,不再接受新的任务
        executor.shutdown();
        // 等待所有任务在指定时间内完成
        executor.awaitTermination(1, TimeUnit.MINUTES);
        log.info("插入数据成功,耗时:{}", System.currentTimeMillis() - time);
    }


}

5.user信息

@Data
@Accessors(chain = true)
@TableName("sys_user")
@ApiModel(value = "SysUser对象", description = "用户信息")
public class User implements Serializable {


    @TableId(value = "SU_CODE" ,type = IdType.ID_WORKER)
    @ApiModelProperty(value = "用户编码")
    private String suCode;

    @TableField("SU_NAME")
    @ApiModelProperty(value = "用户姓名")
    private String suName;
}

6.运行 localhost:8090/exam/handle

运行结果最终10w条数据仅需要0.8秒
面试官问你怎么写的把代码摔在他脸上

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值