这几天在做分库分表,涉及到数据迁移,然后设计的方案是使用mybatis将数据分批读取出来,每批大概40--50万条数据,然后将查询来的数据再insert进去,发现这个效率很低,程序有卡顿,而且客户端很容易OOM。
找了一下原因就是jdbc默认的读取数据的时候,会将要查询的数据一次性读到内存中,再通过resultSet循环读取出来,这样子40--50万条数据很容易就撑爆内存,然后调研了下发现,其实可以通过jdbc流的方式读取数据,这种方式可以将读取出来的每一条数据查询到客户端,再执行insert操作,这样机器负载就会轻很多,实际操作了下,确实是这样的
上代码
public class StreamTest {
public static void main(String[] args) throws SQLException, InterruptedException {
StreamTest streamTest = new StreamTest();
System.out.println("---------------------------");
streamTest.selectData("select * from t_item_base_snapshot");
System.out.println("---------------------------");
streamTest.selectDataStream("select * from t_item_base_snapshot");
}
public static Connection getSqlConnection() {
String url = "";
String user = "";
String password = "";
String driverClass = "com.mysql.jdbc.Driver";
Connection connection = null;