ConnectionTest.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import oracle.jdbc.OracleConnection;
  2. import org.dbsyncer.common.util.CollectionUtils;
  3. import org.dbsyncer.common.util.RandomUtil;
  4. import org.dbsyncer.common.util.StringUtil;
  5. import org.dbsyncer.sdk.config.DatabaseConfig;
  6. import org.dbsyncer.sdk.connector.database.DatabaseConnectorInstance;
  7. import org.dbsyncer.sdk.connector.database.ds.SimpleConnection;
  8. import org.dbsyncer.sdk.enums.TableTypeEnum;
  9. import org.dbsyncer.sdk.model.Field;
  10. import org.dbsyncer.sdk.model.Table;
  11. import org.junit.Test;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.jdbc.core.BatchPreparedStatementSetter;
  15. import java.nio.charset.Charset;
  16. import java.sql.*;
  17. import java.time.Instant;
  18. import java.time.LocalDateTime;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.concurrent.*;
  22. /**
  23. * @author AE86
  24. * @version 1.0.0
  25. * @date 2022/4/11 20:19
  26. */
  27. public class ConnectionTest {
  28. private final Logger logger = LoggerFactory.getLogger(getClass());
  29. @Test
  30. public void testByte() {
  31. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(createOracleConfig());
  32. String executeSql = "UPDATE \"my_user\" SET \"name\"=?,\"clo\"=? WHERE \"id\"=?";
  33. int[] execute = connectorInstance.execute(databaseTemplate ->
  34. databaseTemplate.batchUpdate(executeSql, new BatchPreparedStatementSetter() {
  35. @Override
  36. public void setValues(PreparedStatement ps, int i) {
  37. try {
  38. SimpleConnection connection = databaseTemplate.getSimpleConnection();
  39. OracleConnection conn = (OracleConnection) connection.getConnection();
  40. Clob clob = conn.createClob();
  41. clob.setString(1, new String("中文888".getBytes(Charset.defaultCharset())));
  42. ps.setString(1, "hello888");
  43. ps.setClob(2, clob);
  44. ps.setInt(3, 2);
  45. } catch (SQLException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. @Override
  50. public int getBatchSize() {
  51. return 1;
  52. }
  53. })
  54. );
  55. logger.info("execute:{}", execute);
  56. }
  57. @Test
  58. public void testConnection() throws InterruptedException {
  59. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(createSqlServerConfig());
  60. // 模拟并发
  61. final int threadSize = 100;
  62. final ExecutorService pool = Executors.newFixedThreadPool(threadSize);
  63. final CyclicBarrier barrier = new CyclicBarrier(threadSize);
  64. final CountDownLatch latch = new CountDownLatch(threadSize);
  65. for (int i = 0; i < threadSize; i++) {
  66. final int k = i + 3;
  67. pool.submit(() -> {
  68. try {
  69. barrier.await();
  70. // 模拟操作
  71. System.out.println(String.format("%s %s:%s", LocalDateTime.now(), Thread.currentThread().getName(), k));
  72. Object execute = connectorInstance.execute(tem -> tem.queryForObject("select 1", Integer.class));
  73. System.out.println(String.format("%s %s:%s execute=>%s", LocalDateTime.now(), Thread.currentThread().getName(), k, execute));
  74. } catch (InterruptedException e) {
  75. logger.error(e.getMessage());
  76. } catch (BrokenBarrierException e) {
  77. logger.error(e.getMessage());
  78. } catch (Exception e) {
  79. logger.error(e.getMessage());
  80. } finally {
  81. latch.countDown();
  82. }
  83. });
  84. }
  85. try {
  86. latch.await();
  87. logger.info("try to shutdown");
  88. pool.shutdown();
  89. } catch (InterruptedException e) {
  90. logger.error(e.getMessage());
  91. }
  92. TimeUnit.SECONDS.sleep(3);
  93. logger.info("test end");
  94. }
  95. @Test
  96. public void testBatchInsert() {
  97. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(createMysqlConfig());
  98. long begin = Instant.now().toEpochMilli();
  99. final int threadSize = 10;
  100. final ExecutorService pool = Executors.newFixedThreadPool(threadSize);
  101. final String sql = "INSERT INTO `vote_records_copy` (`id`, `user_id`, `vote_num`, `group_id`, `status`, `create_time`) VALUES (?, ?, ?, ?, ?, ?)";
  102. // 模拟1000w条数据
  103. List<Object[]> dataList = new ArrayList<>();
  104. for (int i = 1; i <= 200001; i++) {
  105. // 442001, 'dA8LeJLtX9MgQgDe7H1O', 9620, 1, 2, '2022-11-17 16:35:21'
  106. Object[] args = new Object[6];
  107. args[0] = i;
  108. args[1] = randomUserId(20);
  109. args[2] = RandomUtil.nextInt(1, 9999);
  110. args[3] = RandomUtil.nextInt(0, 3);
  111. args[4] = RandomUtil.nextInt(1, 3);
  112. args[5] = Timestamp.valueOf(LocalDateTime.now());
  113. dataList.add(args);
  114. if (i % 10000 == 0) {
  115. System.out.println(i + "-----------------正在处理");
  116. batchUpdate(connectorInstance, pool, sql, dataList, 1000);
  117. dataList.clear();
  118. }
  119. }
  120. if(!CollectionUtils.isEmpty(dataList)){
  121. System.out.println("-----------------正在处理剩余数据");
  122. batchUpdate(connectorInstance, pool, sql, dataList, 1000);
  123. }
  124. pool.shutdown();
  125. logger.info("总共耗时:{}秒", (Instant.now().toEpochMilli() - begin) / 1000);
  126. }
  127. @Test
  128. public void testBatchUpdate() {
  129. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(createMysqlConfig());
  130. long begin = Instant.now().toEpochMilli();
  131. final int threadSize = 10;
  132. final ExecutorService pool = Executors.newFixedThreadPool(threadSize);
  133. final String sql = "UPDATE `test`.`vote_records` SET `user_id` = ?, `create_time` = now() WHERE `id` = ?";
  134. // 模拟100w条数据
  135. int k = 10;
  136. while (k > 0) {
  137. List<Object[]> dataList = new ArrayList<>();
  138. for (int i = 1; i <= 100000; i++) {
  139. // 'dA8LeJLtX9MgQgDe7H1O', '2022-11-17 16:35:21', 1
  140. Object[] args = new Object[2];
  141. args[0] = randomUserId(20);
  142. args[1] = i;
  143. dataList.add(args);
  144. if (i % 10000 == 0) {
  145. System.out.println(i + "-----------------正在处理");
  146. batchUpdate(connectorInstance, pool, sql, dataList, 1000);
  147. dataList.clear();
  148. }
  149. }
  150. if (!CollectionUtils.isEmpty(dataList)) {
  151. System.out.println("-----------------正在处理剩余数据");
  152. batchUpdate(connectorInstance, pool, sql, dataList, 1000);
  153. }
  154. k--;
  155. }
  156. pool.shutdown();
  157. logger.info("总共耗时:{}秒", (Instant.now().toEpochMilli() - begin) / 1000);
  158. }
  159. @Test
  160. public void testBatchDelete() {
  161. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(createMysqlConfig());
  162. long begin = Instant.now().toEpochMilli();
  163. final int threadSize = 10;
  164. final ExecutorService pool = Executors.newFixedThreadPool(threadSize);
  165. final String sql = "delete from `test`.`vote_records` WHERE `id` = ?";
  166. List<Object[]> dataList = new ArrayList<>();
  167. for (int i = 1; i <= 3259000; i++) {
  168. // 'dA8LeJLtX9MgQgDe7H1O', '2022-11-17 16:35:21', 1
  169. Object[] args = new Object[1];
  170. args[0] = i;
  171. dataList.add(args);
  172. if (i % 10000 == 0) {
  173. System.out.println(i + "-----------------正在处理");
  174. batchUpdate(connectorInstance, pool, sql, dataList, 1000);
  175. dataList.clear();
  176. }
  177. }
  178. if (!CollectionUtils.isEmpty(dataList)) {
  179. System.out.println("-----------------正在处理剩余数据");
  180. batchUpdate(connectorInstance, pool, sql, dataList, 1000);
  181. }
  182. pool.shutdown();
  183. logger.info("总共耗时:{}秒", (Instant.now().toEpochMilli() - begin) / 1000);
  184. }
  185. private final static String STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  186. private String randomUserId(int i) {
  187. StringBuilder s = new StringBuilder();
  188. for (int j = 0; j < i; j++) {
  189. int r = RandomUtil.nextInt(0, 62);
  190. s.append(StringUtil.substring(STR, r, r + 1));
  191. }
  192. return s.toString();
  193. }
  194. private void batchUpdate(DatabaseConnectorInstance connectorInstance, ExecutorService pool, String sql, List<Object[]> dataList, int batchSize) {
  195. int total = dataList.size();
  196. int taskSize = total % batchSize == 0 ? total / batchSize : total / batchSize + 1;
  197. final CountDownLatch latch = new CountDownLatch(taskSize);
  198. int fromIndex = 0;
  199. int toIndex = batchSize;
  200. for (int i = 0; i < taskSize; i++) {
  201. final List<Object[]> data;
  202. if (toIndex > total) {
  203. toIndex = fromIndex + (total % batchSize);
  204. data = dataList.subList(fromIndex, toIndex);
  205. } else {
  206. data = dataList.subList(fromIndex, toIndex);
  207. fromIndex += batchSize;
  208. toIndex += batchSize;
  209. }
  210. pool.submit(() -> {
  211. try {
  212. connectorInstance.execute(databaseTemplate -> databaseTemplate.batchUpdate(sql, data));
  213. } catch (Exception e) {
  214. logger.error(e.getMessage());
  215. } finally {
  216. latch.countDown();
  217. }
  218. });
  219. }
  220. try {
  221. latch.await();
  222. } catch (InterruptedException e) {
  223. logger.error(e.getMessage());
  224. }
  225. }
  226. @Test
  227. public void testReadSchema() {
  228. getTables(createOracleConfig(), "test", "AE86", "MY_ORG");
  229. getTables(createOracleConfig(), "test", "AE86", null);
  230. getTables(createMysqlConfig(), "test", "root", "MY_ORG");
  231. getTables(createMysqlConfig(), "test", "root", null);
  232. getTables(createSqlServerConfig(), "test", "dbo", "MY_ORG");
  233. getTables(createSqlServerConfig(), "test", "dbo", null);
  234. getTables(createPostgresConfig(), "postgres", "public", "MY_ORG");
  235. getTables(createPostgresConfig(), "postgres", "public", null);
  236. }
  237. @Test
  238. public void testGetColumnsDetails() {
  239. final String schema = "root";
  240. final String tableNamePattern = "sw_test";
  241. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(createMysqlConfig());
  242. connectorInstance.execute(databaseTemplate -> {
  243. SimpleConnection connection = databaseTemplate.getSimpleConnection();
  244. Connection conn = connection.getConnection();
  245. String databaseCatalog = conn.getCatalog();
  246. String schemaNamePattern = null == schema ? conn.getSchema() : schema;
  247. List<Field> fields = new ArrayList<>();
  248. DatabaseMetaData metaData = conn.getMetaData();
  249. ResultSet columnMetadata = metaData.getColumns(databaseCatalog, schemaNamePattern, tableNamePattern, null);
  250. while (columnMetadata.next()) {
  251. String columnName = columnMetadata.getString(4);
  252. int columnType = columnMetadata.getInt(5);
  253. String typeName = columnMetadata.getString(6);
  254. fields.add(new Field(columnName, typeName, columnType));
  255. }
  256. return fields;
  257. });
  258. }
  259. private List<Table> getTables(DatabaseConfig config, final String catalog, final String schema, final String tableNamePattern) {
  260. final DatabaseConnectorInstance connectorInstance = new DatabaseConnectorInstance(config);
  261. List<Table> tables = new ArrayList<>();
  262. connectorInstance.execute(databaseTemplate -> {
  263. SimpleConnection connection = databaseTemplate.getSimpleConnection();
  264. Connection conn = connection.getConnection();
  265. String databaseCatalog = null == catalog ? conn.getCatalog() : catalog;
  266. String schemaNamePattern = null == schema ? conn.getSchema() : schema;
  267. String[] types = {TableTypeEnum.TABLE.getCode(), TableTypeEnum.VIEW.getCode(), TableTypeEnum.MATERIALIZED_VIEW.getCode()};
  268. final ResultSet rs = conn.getMetaData().getTables(databaseCatalog, schemaNamePattern, tableNamePattern, types);
  269. while (rs.next()) {
  270. final String tableName = rs.getString("TABLE_NAME");
  271. final String tableType = rs.getString("TABLE_TYPE");
  272. tables.add(new Table(tableName, tableType));
  273. }
  274. return tables;
  275. });
  276. logger.info("\r 表总数{}", tables.size());
  277. tables.forEach(t -> logger.info("{} {}", t.getName(), t.getType()));
  278. return tables;
  279. }
  280. private DatabaseConfig createSqlServerConfig() {
  281. DatabaseConfig config = new DatabaseConfig();
  282. config.setUrl("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test");
  283. config.setUsername("sa");
  284. config.setPassword("123");
  285. config.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  286. return config;
  287. }
  288. private DatabaseConfig createOracleConfig() {
  289. DatabaseConfig config = new DatabaseConfig();
  290. config.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:ORCL");
  291. config.setUsername("ae86");
  292. config.setPassword("123");
  293. config.setDriverClassName("oracle.jdbc.OracleDriver");
  294. return config;
  295. }
  296. private DatabaseConfig createMysqlConfig() {
  297. DatabaseConfig config = new DatabaseConfig();
  298. config.setUrl("jdbc:mysql://127.0.0.1:3305/test?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&useSSL=false&verifyServerCertificate=false&autoReconnect=true&failOverReadOnly=false");
  299. config.setUsername("root");
  300. config.setPassword("123");
  301. config.setDriverClassName("com.mysql.cj.jdbc.Driver");
  302. return config;
  303. }
  304. private DatabaseConfig createPostgresConfig() {
  305. DatabaseConfig config = new DatabaseConfig();
  306. config.setUrl("jdbc:postgresql://127.0.0.1:5432/postgres");
  307. config.setUsername("postgres");
  308. config.setPassword("123456");
  309. config.setDriverClassName("org.postgresql.Driver");
  310. return config;
  311. }
  312. }