如何解决mysql 批处理模式 测试 1:测试 2:测试 3:
我最近尝试了大量的插入语句。找了半天,发现MysqL支持批处理模式,所以用批处理模式做了一个测试。
测试 1:
@Test
public void testSingleService() {
try {
for (int i = 0; i < 10000; i++) {
iLostProductService.insertProduct(new Product("testSingleService" + i));
}
} catch (Exception e) {
e.printstacktrace();
}
}
mybatis.xml
<sql id = "basesql">
product_name
</sql>
<insert id="insertProduct" parameterType="com.team.lof.model.Product">
insert into product (<include refid="basesql"></include>) values (#{name})
</insert>
这需要很长时间,我放弃了。
测试 2:
@Test
public void testBatchService() {
List<Product> productList = new ArrayList<Product>();
for (int i = 0; i < 10000; i++) {
productList.add(new Product("2227testBatchService" + i));
}
try {
iLostProductService.insertProductList(productList);
} catch (Exception e) {
e.printstacktrace();
}
}
mybatis.xml
<insert id="insertProductList">
insert into product (<include refid="basesql"></include>) values
<foreach collection="productList" item="product" separator=",">
(#{product.name})
</foreach>
</insert>
需要 1s 329ms,相当快。
测试 3:
开启批处理模式,spring.datasource.url需要配置rewriteBatchedStatements=true
spring.datasource.url=jdbc:MysqL://127.0.0.1:3306/lof?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT&rewriteBatchedStatements=true
@Test
public void testBatchExcutorService() {
sqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
ProductDao batchProductDao = sqlSession.getMapper(ProductDao.class);
for (int i = 0; i < 10000; i++) {
batchProductDao.insertProduct(new Product("2047testBatchExcutorService" + i));
}
} catch (Exception e) {
e.printstacktrace();
} finally {
sqlSession.commit();
sqlSession.close();
}
}
mybatis.xml
<insert id="insertProduct" parameterType="com.team.lof.model.Product">
insert into product (<include refid="basesql"></include>) values (#{name})
</insert>
最快需要 1s 119ms。
我分别捕获并分析了数据包。测试 1 中每个数据包的大小为 151 字节,测试 2 和测试 3 中每个数据包的大小为 1466 字节。测试 2 总共发送了 634 个数据包,总大小为 575925 字节。 3 总共发送了 452 个数据包,总大小为 392,882 字节。我查看了test 2和test 3的包数据,大小为1466字节,发现test 3的包被压缩了。这是快速批处理模式的原因吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。