2017-07-02 119 views
-2

mysql server config 这里是mysql配置,一个非常简单的表,innodb和没有太多索引,但有时插入op太慢,有人可以告诉我为什么吗?mysql插入太慢

public Long insertCoursewarePage(Env env, Long coursewareId, Integer pageType, String teacherId) throws SQLException { 
    env.logTiming("beforeGetConnection"); 
    Connection conn = MySql.getInst_education_biz().getConnection(); 
    env.logTiming("afterGetConnection"); 
    PreparedStatement pstmt = null; 
    ResultSet rs = null; 
    String sql = "INSERT INTO `courseware_page`(`courseware_id`, `page_type`, `teacher_id`, `create_time`) VALUES(?,?,?,?)"; 
    try { 
     pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); 
     env.logTiming("afterPrepareStatement"); 
     pstmt.setLong(1, coursewareId); 
     pstmt.setInt(2, pageType); 
     pstmt.setString(3, teacherId); 
     pstmt.setLong(4, System.currentTimeMillis()); 
     pstmt.executeUpdate(); 
     env.logTiming("afterExecuteUpdate"); 
     rs = pstmt.getGeneratedKeys(); 
     env.logTiming("afterGetGeneratedKeys"); 
     if (rs.next()) { 
      return rs.getLong(1); 
     } 
    } finally { 
     MySql.closeConnection(rs, pstmt, conn); 
    } 
    return null; 
} 
/** 
Here is my java code, use jdbc get a connection and I profiled it and the result is below here. 
beforeGetConnection=14 
afterGetConnection=20 
afterPrepareStatement=20 
afterExecuteUpdate=5344 
afterGetGeneratedKeys=5345 
mysql server is on a dell r820, SSD, 64 core cpu, 320G memory, it seems no any problem.so could anybody tell me why 
**/ 
+0

[3]:https://i.stack.imgur.com/C4ZN7.png [4]:https://i.stack.imgur.com/uwNwL .png [5]:https://i.stack.imgur.com/xc5sR.png – zhouxun

+3

请将**全部**相关代码视为文本。代码编辑器就是为此目的而存在的。 – BackSlash

+0

对不起,我没有权利回复你,代码img在这里https://i.stack.imgur.com/vm3GN.png – zhouxun

回答

1

这可能是因为每次你要插入你打开与Connection conn = MySql.getInst_education_biz().getConnection();的连接,然后你执行你的查询和事后关闭MySql.closeConnection(rs, pstmt, conn);

你插入时可能会低,但打开和关闭每一个连接查询是昂贵的。如果经常查询数据库,则可能需要使用连接池,该连接池只会“暂停”连接并在需要时“恢复”连接。以下是使用它的一些原因:https://plumbr.eu/blog/io/acquiring-jdbc-connections-what-can-possibly-go-wrong

+0

谢谢n0xew,但我敢肯定,有没有获得连接的业务。因为我记录了执行时间,从线程开始到'env.logTiming(“beforeGetConnection”);'程序花费14ms,并且当它运行到'Connection conn = MySql.getInst_education_biz()。getConnection();'它是20 ms,这意味着只需要6 ms的连接,并且您可以在代码下看到其他成本。大部分时间花费在'pstmt.executeUpdate();'我在mysql服务器cli上尝试了这个sql,它得到了相同的结果。 – zhouxun

+0

我的mysql服务器硬件配置也在我的java代码下面的注释中。 – zhouxun

+0

我很确定数据库在连接关闭后会执行一些资源释放,因此需要更多时间来处理可能的传入连接和查询。这当然取决于你的查询频率。 无论如何,更新我的答案使用'ConnectionPool',它只能帮助你解决其他问题。 – n0xew