mysql與redis快速插入資料
阿新 • • 發佈:2018-11-26
1.多執行緒的使用
java最優效能執行緒數與cpu執行緒數有關,cpu每個執行緒同時只能做一件事,但java程式執行時間分為計算時間與非計算時間如IO讀取等操作耗時,
開啟2-3倍的cpu執行緒數的執行緒一般情況下是追求效能優先的最優選擇,因為過多的執行緒數會浪費一些資源在cpu執行緒的切換上
2.mySql批量插入
mySql快速批量插入比較合適的方法是通過jdbc的批處理插入資料,程式碼如下:
public void insertBatch(int i) { /* 資料來源 */ Connection connection = null; try { // 1.載入MySQL的驅動 Class.forName("com.mysql.jdbc.Driver"); /* 連線資料庫的引數 */ connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); /* 插入的sql */ String sql = "INSERT into sys_user(user_lid,user_state) VALUES(?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); /* 迴圈插入 */ for (int i = count * 10000 + 1; i <= count * 10000 + 10000; i++) { preparedStatement.setString(1, i + ""); preparedStatement.setInt(2, 1); preparedStatement.addBatch();// 把資料放入快取區 if (i % 10000 == 0) { // 重新整理快取區 preparedStatement.executeBatch(); preparedStatement.clearBatch();// 清除之前的資料 } } // 重新整理快取區 preparedStatement.executeBatch(); preparedStatement.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
如開啟事務並手動提交會效率更高
3.Redis批量插入
public static void main(String[] args) throws Exception { Jedis jedis = new Jedis("localhost", 6379); //redis密碼 jedis.auth("root"); //構建Pipeline物件 Pipeline pipelined = jedis.pipelined(); for (int i = 1; i <= 100000; i++) { pipelined.set(i + ":token", i + ""); pipelined.set("token:" + i, i + ""); } //執行Pipeline物件 pipelined.sync(); //關閉連線 jedis.close(); }