mybatisPlus 一次插入10w条数据遇到的问题
mybatisPlus 自带的insertBatch 是逐条插入,性能很差,应该禁止使用,扩展使其变为一次批量插入
扩展插入插入方式insertBatchSomeColumn
我的服务器比较垃圾,带宽较低,所以正式环境中不会出现插入10w条需要9秒的情况,本内容插入时间仅供参考,同时也思考到带宽瓶颈对我们接口响应速度的影响
新增接口 EasyBaseMapper
。
public interface EasyBaseMapper<T> extends BaseMapper<T> {
/**
* 批量插入 仅适用于mysql
*
* @param entityList 实体列表
* @return 影响行数
*/
Integer insertBatchSomeColumn(Collection<T> entityList);
}
新增类 EasySqlInjector
。
public class EasySqlInjector extends DefaultSqlInjector {
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
// TODO Auto-generated method stub
List<AbstractMethod> methodList = super.getMethodList(mapperClass,tableInfo);
methodList.add(new InsertBatchSomeColumn()); // 添加InsertBatchSomeColumn方法
return methodList;
}
``
MybatisPlusConfig 加入bean管理
。
@Bean
public EasySqlInjector easySqlInjector () {
return new EasySqlInjector();
}
修改数据库一次能插入的数据量
一次插入10w条数据 抛出异常
。
2022-04-07 21:47:14.438 ERROR 6692 --- [nio-8082-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.TransientDataAccessResourceException:
### Error updating database. Cause: com.mysql.cj.jdbc.exceptions.PacketTooBigException: Packet for query is too large (12,477,956 > 4,194,304). You can change this value on the server by setting the 'max_allowed_packet' variable.
原因:数据库一次允许插入的数据量为4,194,304 ,本次10w条大小为12,477,956 超出
修改数据库的max_allowed_packet 值 如果没有 手动添加这个值
vi /etc/my.cnf
max_allowed_packet = 524288000
service mysqld restart
修改成功
经过优化之后插入10w条数据时间为9.46s