数据库写入性能测试小工具

文章来自:http://blog.csdn.net/kongxx/article/details/42360663

今天工作需要要写一个小工具来测试一下数据库的写入性能,需要支持多并发,并且支持调整事务提交记录大小,所以就用Java写了一个,就一个类,比较简单但是基本功能都有了,下面看看代码实现

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.PreparedStatement;  
  4. import java.sql.ResultSet;  
  5. import java.sql.ResultSetMetaData;  
  6. import java.sql.SQLException;  
  7. import java.sql.Statement;  
  8. import java.sql.Timestamp;  
  9. import java.sql.Types;  
  10. import java.util.ArrayList;  
  11. import java.util.Calendar;  
  12. import java.util.Collections;  
  13. import java.util.Formatter;  
  14. import java.util.LinkedHashMap;  
  15. import java.util.List;  
  16. import java.util.Map;  
  17. import java.util.Random;  
  18. import java.util.UUID;  
  19. import java.util.concurrent.CountDownLatch;  
  20. import java.util.logging.Level;  
  21. import java.util.logging.Logger;  
  22.    
  23. public class InsertTest {  
  24.    
  25.     private static Logger logger = Logger.getLogger(InsertTest.class.getName());  
  26.    
  27.     private static final String DB_DRIVER = "com.ibm.db2.jcc.DB2Driver";  
  28.     private static final String DB_URL = "jdbc:db2://9.111.251.152:50000/padb";  
  29.     private static final String DB_USERNAME = "db2inst";  
  30.     private static final String DB_PASSWORD = "Letmein";  
  31.    
  32.     private static Random random = new Random(10000);  
  33.    
  34.     private static final String TABLE_NAME = "BENCHMARK";  
  35.    
  36.     private int batchSize;  
  37.    
  38.     private int concurrent;  
  39.    
  40.     private int sampling;  
  41.    
  42.     public static void main(String[] args) throws Exception {  
  43.         printHeader();  
  44.    
  45.         int[] concurrentList = new int[]{151020};  
  46.         int[] batchSizeList = new int[] {10002000500010000};  
  47.         for (int concurrent : concurrentList) {  
  48.             for (int batchSize : batchSizeList) {  
  49.                 new InsertTest(batchSize, concurrent).run(true);  
  50.             }  
  51.             Thread.sleep(10000);  
  52.         }  
  53.     }  
  54.    
  55.     public InsertTest(final int batchSize, final int concurrent) throws Exception {  
  56.         this.batchSize = batchSize;  
  57.         this.concurrent = concurrent;  
  58.         this.sampling = 100;  
  59.     }  
  60.    
  61.     public InsertTest(final int batchSize, final int concurrent, final int sampling) throws Exception {  
  62.         this.batchSize = batchSize;  
  63.         this.concurrent = concurrent;  
  64.         this.sampling = sampling;  
  65.     }  
  66.    
  67.     public void run(boolean printResult) throws Exception {  
  68.         final List<Long> results = Collections.synchronizedList(new ArrayList<Long>());  
  69.         final CountDownLatch startGate = new CountDownLatch(concurrent);  
  70.         final CountDownLatch endGate = new CountDownLatch(concurrent);  
  71.    
  72.         for (int idxConcurrent = 0; idxConcurrent < concurrent; idxConcurrent++) {  
  73.             new Thread(new Runnable() {  
  74.                 public void run() {  
  75.                     startGate.countDown();  
  76.                     try {  
  77.                         long time = execute();  
  78.                         long avg = batchSize * sampling * 1000 / time;;  
  79.                         results.add(Long.valueOf(avg));  
  80.                     } catch(Exception ex) {  
  81.                         ex.printStackTrace();  
  82.                     } finally {  
  83.                         endGate.countDown();  
  84.                     }  
  85.                 }  
  86.             }).start();  
  87.         }  
  88.         endGate.await();  
  89.    
  90.         Collections.sort(results);  
  91.    
  92.         if (printResult) {  
  93.             printResult(batchSize, concurrent, results);  
  94.         }  
  95.     }  
  96.    
  97.     public long execute() throws Exception {  
  98.         Connection conn = getConnection();  
  99.         Map<String, Integer> columns = queryTableColumns(conn);  
  100.         String insertSQL = generateInsertSQL(columns);  
  101.         PreparedStatement ps = conn.prepareStatement(insertSQL);  
  102.         try {  
  103.             long start = System.currentTimeMillis();  
  104.             for (int i = 0; i < sampling; i++) {  
  105.                 execute(conn, ps, columns);  
  106.             }  
  107.             long stop = System.currentTimeMillis();  
  108.             return stop - start;  
  109.         } catch(Exception ex) {  
  110.             logger.log(Level.SEVERE, null, ex);  
  111.             conn.rollback();  
  112.             conn.close();  
  113.             throw ex;  
  114.         } finally {  
  115.             conn.close();  
  116.         }  
  117.     }  
  118.    
  119.     public void execute(Connection conn, PreparedStatement ps, Map<String, Integer> columns) throws Exception {  
  120.         try {  
  121.             for (int idx = 0; idx < batchSize; idx++) {  
  122.                 int idxColumn = 1;  
  123.                 for (String column : columns.keySet()) {  
  124.                     if (column.equalsIgnoreCase("ID")) {  
  125.                         ps.setObject(idxColumn, UUID.randomUUID().toString());  
  126.                     } else {  
  127.                         ps.setObject(idxColumn, generateColumnValue(columns.get(column)));  
  128.                     }  
  129.                     idxColumn ++;  
  130.                 }  
  131.                 ps.addBatch();  
  132.             }  
  133.             ps.executeBatch();  
  134.             conn.commit();  
  135.    
  136.             ps.clearBatch();  
  137.         } catch (SQLException ex) {  
  138.             logger.log(Level.SEVERE, null, ex);  
  139.             if (null != ex.getNextException()) {  
  140.                 logger.log(Level.SEVERE, null, ex.getNextException());  
  141.             }  
  142.             conn.rollback();  
  143.             throw ex;  
  144.         }  
  145.     }  
  146.    
  147.     private String generateInsertSQL(Map<String, Integer> columns) throws SQLException {  
  148.         StringBuilder sb = new StringBuilder();  
  149.         StringBuffer sbColumns = new StringBuffer();  
  150.         StringBuffer sbValues = new StringBuffer();  
  151.    
  152.         sb.append("INSERT INTO ").append(TABLE_NAME);  
  153.    
  154.         for (String column : columns.keySet()) {  
  155.             if (sbColumns.length() > 0) {  
  156.                 sbColumns.append(",");  
  157.                 sbValues.append(",");  
  158.             }  
  159.             sbColumns.append(column);  
  160.             sbValues.append("?");  
  161.         }  
  162.         sb.append("(").append(sbColumns).append(")");  
  163.         sb.append("VALUES");  
  164.         sb.append("(").append(sbValues).append(")");  
  165.         return sb.toString();  
  166.     }  
  167.    
  168.     private Map<String, Integer> queryTableColumns(Connection conn) throws Exception {  
  169.         Map<String, Integer> columns = new LinkedHashMap<String, Integer>();  
  170.         String sql = "SELECT * FROM " + TABLE_NAME + " WHERE 1=0";  
  171.         Statement stmt = conn.createStatement();  
  172.         ResultSet rs = stmt.executeQuery(sql);  
  173.         ResultSetMetaData rsmd = rs.getMetaData();  
  174.         for (int i = 1; i <= rsmd.getColumnCount(); i++) {  
  175.             columns.put(rsmd.getColumnName(i), rsmd.getColumnType(i));  
  176.         }  
  177.         return columns;  
  178.     }  
  179.    
  180.     private Object generateColumnValue(int type) {  
  181.         Object obj = null;  
  182.         switch (type) {  
  183.             case Types.DECIMAL:  
  184.             case Types.NUMERIC:  
  185.             case Types.DOUBLE:  
  186.             case Types.FLOAT:  
  187.             case Types.REAL:  
  188.             case Types.BIGINT:  
  189.             case Types.TINYINT:  
  190.             case Types.SMALLINT:  
  191.             case Types.INTEGER:  
  192.                 obj = random.nextInt(10000);  
  193.                 break;  
  194.             case Types.DATE:  
  195.                 obj = Calendar.getInstance().getTime();  
  196.                 break;  
  197.             case Types.TIMESTAMP:  
  198.                 obj = new Timestamp(System.currentTimeMillis());  
  199.                 break;  
  200.             default:  
  201.                 obj = String.valueOf(random.nextInt(10000));  
  202.                 break;  
  203.         }  
  204.         return obj;  
  205.     }  
  206.    
  207.     private Connection getConnection() throws Exception {  
  208.         Class.forName(DB_DRIVER);  
  209.         Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);  
  210.         conn.setAutoCommit(false);  
  211.         return conn;  
  212.     }  
  213.    
  214.     private static void printHeader() {  
  215.         StringBuilder sb = new StringBuilder();  
  216.         sb.append("\n");  
  217.         sb.append(new Formatter().format("%15s|%15s|%15s|%15s|%15s""BATCH_SIZE""CONCURRENT""AVG (r/s)""MIN (r/s)""MAX (r/s)"));  
  218.         System.out.println(sb.toString());  
  219.     }  
  220.    
  221.     private static void printResult(int batch, int concurrent, List<Long> results) {  
  222.         Long total = Long.valueOf(0);  
  223.         for (Long result : results) {  
  224.             total += result;  
  225.         }  
  226.         StringBuilder sb = new StringBuilder();  
  227.         sb.append(new Formatter().format("%15s|%15s|%15s|%15s|%15s", batch, concurrent, (total/results.size()), results.get(0), results.get(results.size() - 1)));  
  228.         System.out.println(sb.toString());  
  229.     }  
  230. }  

要运行测试需要
1. 修改数据库的配置信息
2. 修改TABLE_NAME指定数据库里需要测试的表名,测试程序会查询这个表的定义来生成写入SQL语句
3. 修改concurrentList指定需要测试并发数列表,默认测试1,5,10,20个并发
4. 修改batchSizeList指定每次测试的事务提交记录数据,默认是1000,2000,5000,10000

最后运行测试,会生成类似下面的结果

  1. BATCH_SIZE|     CONCURRENT|      AVG (r/s)|      MIN (r/s)|      MAX (r/s)  
  2.       1000|              1|            ...|            ...|            ...  
  3.       2000|              1|            ...|            ...|            ...  
  4.       5000|              1|            ...|            ...|            ...  
  5.      10000|              1|            ...|            ...|            ...  
  6.       1000|              5|            ...|            ...|            ...  
  7.       2000|              5|            ...|            ...|            ...  
  8.       5000|              5|            ...|            ...|            ...  
  9.      10000|              5|            ...|            ...|            ... 

猜你喜欢

转载自ximeng1234.iteye.com/blog/2206477