在很多面试官面前都会问道如果添加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秒
面试官问你怎么写的把代码摔在他脸上