张泳健 5 年之前
當前提交
9b7389bf65
共有 31 個文件被更改,包括 1333 次插入0 次删除
  1. 15 0
      .gitignore
  2. 14 0
      README.md
  3. 4 0
      config/application-dev.yml
  4. 2 0
      config/application.yml
  5. 106 0
      pom.xml
  6. 97 0
      src/main/java/com/vcarecity/cvs/BuildPartitionSQL.java
  7. 32 0
      src/main/java/com/vcarecity/cvs/MySQLCSVWriter.java
  8. 70 0
      src/main/java/com/vcarecity/cvs/MySQLStarter.java
  9. 55 0
      src/main/java/com/vcarecity/cvs/TestInsertData.java
  10. 73 0
      src/main/java/com/vcarecity/cvs/core/AutoMapper.java
  11. 15 0
      src/main/java/com/vcarecity/cvs/core/JavaMapColumn.java
  12. 51 0
      src/main/java/com/vcarecity/cvs/core/ReflectionUtil.java
  13. 137 0
      src/main/java/com/vcarecity/cvs/csv/DataBuilder.java
  14. 13 0
      src/main/java/com/vcarecity/cvs/csv/SQLCSVWriter.java
  15. 68 0
      src/main/java/com/vcarecity/cvs/entity/CheckRecordEntity.java
  16. 18 0
      src/main/java/com/vcarecity/cvs/entity/WebSiteEntity.java
  17. 19 0
      src/main/java/com/vcarecity/cvs/factory/ResultHandlerFactory.java
  18. 60 0
      src/main/java/com/vcarecity/cvs/module/MySQLModule.java
  19. 21 0
      src/main/java/com/vcarecity/cvs/module/PropertiesModule.java
  20. 12 0
      src/main/java/com/vcarecity/cvs/properties/AppProperties.java
  21. 14 0
      src/main/java/com/vcarecity/cvs/properties/DbProperties.java
  22. 22 0
      src/main/java/com/vcarecity/cvs/service/ResultHandlerService.java
  23. 27 0
      src/main/java/com/vcarecity/cvs/service/SQLQueryService.java
  24. 188 0
      src/main/java/com/vcarecity/cvs/service/impl/CSVResultHandlerServiceImpl.java
  25. 56 0
      src/main/java/com/vcarecity/cvs/service/impl/MySQLQueryServiceImpl.java
  26. 42 0
      src/main/java/com/vcarecity/cvs/service/impl/MySQLResultHandlerServiceImpl.java
  27. 55 0
      src/main/java/com/vcarecity/cvs/service/impl/OracleQueryServiceImpl.java
  28. 1 0
      src/main/lombok.config
  29. 38 0
      src/main/resources/logback-test.xml
  30. 7 0
      src/test/java/com/vcarecity/cvs/service/impl/CSVResultHandlerServiceImplTest.java
  31. 1 0
      src/test/lombok.config

+ 15 - 0
.gitignore 查看文件

@@ -0,0 +1,15 @@
1
+
2
+
3
+*.iml
4
+*.log
5
+*.class
6
+*.jar
7
+*.csv
8
+*.xls
9
+*.xlsx
10
+*.zip
11
+
12
+logs/
13
+target/
14
+build/
15
+.idea/

+ 14 - 0
README.md 查看文件

@@ -0,0 +1,14 @@
1
+
2
+
3
+
4
+
5
+````
6
+LOAD DATA INFILE '/var/lib/mysql-files/check_record_0006'
7
+INTO TABLE T_CHECK_RECORD_1
8
+FIELDS 
9
+    TERMINATED BY '\t'
10
+    ENCLOSED BY '\"'
11
+    ESCAPED BY '\\'
12
+LINES TERMINATED BY '\n'
13
+(CHECK_RECORD_ID,STAMP,USER_ID,CHECK_POINTS_ID,IS_NORMAL,IS_LATENT_DANGER,LATENT_DANGER_TYPE,LATENT_DANGER_DESC,UNDETECTED_NUM,LON,LAT,RULE_ID,IS_DEAL,STARTDATE,ENDDATE,VALID_CHECK,UPDATESTAMP);
14
+````

+ 4 - 0
config/application-dev.yml 查看文件

@@ -0,0 +1,4 @@
1
+database:
2
+  url: jdbc:mysql:replication://192.168.10.210:6446,192.168.10.210:6447/fmmp?serverTimezone=Asia/Shanghai
3
+  user: root
4
+  password: R00T@mysql

+ 2 - 0
config/application.yml 查看文件

@@ -0,0 +1,2 @@
1
+profile:
2
+  active: dev

+ 106 - 0
pom.xml 查看文件

@@ -0,0 +1,106 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project xmlns="http://maven.apache.org/POM/4.0.0"
3
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
+    <modelVersion>4.0.0</modelVersion>
6
+
7
+    <groupId>com.vcarecity.csv</groupId>
8
+    <artifactId>db-data-to-csv</artifactId>
9
+    <version>1.0.0</version>
10
+    <build>
11
+        <plugins>
12
+            <plugin>
13
+                <groupId>org.apache.maven.plugins</groupId>
14
+                <artifactId>maven-compiler-plugin</artifactId>
15
+                <configuration>
16
+                    <source>8</source>
17
+                    <target>8</target>
18
+                </configuration>
19
+            </plugin>
20
+        </plugins>
21
+    </build>
22
+
23
+
24
+    <dependencies>
25
+
26
+        <dependency>
27
+            <groupId>mysql</groupId>
28
+            <artifactId>mysql-connector-java</artifactId>
29
+            <version>8.0.18</version>
30
+        </dependency>
31
+        <dependency>
32
+            <groupId>org.apache.commons</groupId>
33
+            <artifactId>commons-text</artifactId>
34
+            <version>1.8</version>
35
+        </dependency>
36
+
37
+
38
+        <dependency>
39
+            <groupId>org.apache.commons</groupId>
40
+            <artifactId>commons-csv</artifactId>
41
+            <version>1.7</version>
42
+        </dependency>
43
+        <dependency>
44
+            <groupId>org.slf4j</groupId>
45
+            <artifactId>slf4j-api</artifactId>
46
+            <version>1.7.29</version>
47
+        </dependency>
48
+        <dependency>
49
+            <groupId>ch.qos.logback</groupId>
50
+            <artifactId>logback-classic</artifactId>
51
+            <version>1.2.3</version>
52
+        </dependency>
53
+        <dependency>
54
+            <groupId>org.projectlombok</groupId>
55
+            <artifactId>lombok</artifactId>
56
+            <version>1.18.10</version>
57
+            <scope>provided</scope>
58
+        </dependency>
59
+
60
+        <dependency>
61
+            <groupId>com.zaxxer</groupId>
62
+            <artifactId>HikariCP</artifactId>
63
+            <version>3.4.1</version>
64
+        </dependency>
65
+        <dependency>
66
+            <groupId>com.google.inject</groupId>
67
+            <artifactId>guice</artifactId>
68
+            <version>4.2.2</version>
69
+        </dependency>
70
+        <dependency>
71
+            <groupId>com.google.inject.extensions</groupId>
72
+            <artifactId>guice-assistedinject</artifactId>
73
+            <version>4.2.2</version>
74
+        </dependency>
75
+
76
+        <dependency>
77
+            <groupId>com.fasterxml.jackson.dataformat</groupId>
78
+            <artifactId>jackson-dataformat-yaml</artifactId>
79
+            <version>2.10.1</version>
80
+        </dependency>
81
+        <dependency>
82
+            <groupId>com.fasterxml.jackson.core</groupId>
83
+            <artifactId>jackson-databind</artifactId>
84
+            <version>2.10.1</version>
85
+        </dependency>
86
+
87
+        <dependency>
88
+            <groupId>me.yuxiaoyao.lang</groupId>
89
+            <artifactId>configuration-loader</artifactId>
90
+            <version>2.0.0</version>
91
+        </dependency>
92
+
93
+        <dependency>
94
+            <groupId>org.apache.shardingsphere</groupId>
95
+            <artifactId>sharding-jdbc-core</artifactId>
96
+            <version>4.0.0-RC2</version>
97
+        </dependency>
98
+        <dependency>
99
+            <groupId>javax.persistence</groupId>
100
+            <artifactId>persistence-api</artifactId>
101
+            <version>1.0.2</version>
102
+        </dependency>
103
+
104
+    </dependencies>
105
+
106
+</project>

+ 97 - 0
src/main/java/com/vcarecity/cvs/BuildPartitionSQL.java 查看文件

@@ -0,0 +1,97 @@
1
+package com.vcarecity.cvs;
2
+
3
+import lombok.extern.slf4j.Slf4j;
4
+
5
+import java.time.LocalDate;
6
+import java.time.format.DateTimeFormatter;
7
+import java.util.ArrayList;
8
+import java.util.List;
9
+
10
+/**
11
+ * @author Kerry on 19/11/25
12
+ * <p>
13
+ * <p>
14
+ * 创建表分区 datetime
15
+ */
16
+
17
+@Slf4j
18
+public class BuildPartitionSQL {
19
+
20
+    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
21
+
22
+
23
+    public static void main(String[] args) {
24
+        BuildPartitionSQL buildPartitionSQL = new BuildPartitionSQL();
25
+        buildPartitionSQL.partitionFirstSql("T_CHECK_RECORD_1", "stamp", "2016-08-23", "2019-11-21", PartitionType.MONTH);
26
+    }
27
+
28
+
29
+    public String partitionFirstSql(String table, String field, String from, String to, PartitionType partitionType) {
30
+        return partitionFirstSql(table, field, LocalDate.parse(from, DATE_FORMATTER), LocalDate.parse(to, DATE_FORMATTER), partitionType);
31
+    }
32
+
33
+    public String partitionFirstSql(String table, String field, LocalDate from, LocalDate to, PartitionType partitionType) {
34
+
35
+        final String[] strings = partitionSql(from, to, partitionType);
36
+        final String join = String.join(",\n", strings);
37
+
38
+        String pre = "ALTER TABLE " + table + " PARTITION BY RANGE (TO_DAYS(" + field + ")) (";
39
+
40
+
41
+        logger.info("--------------------------first create table partition SQL.--------------------------");
42
+
43
+        String s = pre + "\n" + join + "\n" + ")";
44
+        System.out.println(s);
45
+
46
+        logger.info("--------------------------first create table partition SQL.--------------------------");
47
+        return s;
48
+    }
49
+
50
+    public String[] partitionSql(LocalDate from, LocalDate to, PartitionType partitionType) {
51
+        LocalDate index = from;
52
+        to = plusDateByType(to, partitionType);
53
+
54
+        List<String> partitionSqls = new ArrayList<>();
55
+        while (index.isBefore(to)) {
56
+            String pName = partitionType.getFormatter().format(index);
57
+            index = plusDateByType(index, partitionType);
58
+            final String format = DATE_FORMATTER.format(index);
59
+            String alter = "PARTITION p" + pName + " VALUES LESS THAN (TO_DAYS('" + format + "')) ENGINE = INNODB";
60
+            partitionSqls.add(alter);
61
+        }
62
+        return partitionSqls.toArray(new String[]{});
63
+    }
64
+
65
+    private enum PartitionType {
66
+        /**
67
+         * 天
68
+         */
69
+        DAY("yyyyMMdd"),
70
+        /**
71
+         * 月
72
+         */
73
+        MONTH("yyyyMM");
74
+        DateTimeFormatter formatter;
75
+
76
+        PartitionType(String format) {
77
+            this.formatter = DateTimeFormatter.ofPattern(format);
78
+        }
79
+
80
+        public DateTimeFormatter getFormatter() {
81
+            return formatter;
82
+        }
83
+    }
84
+
85
+    private static LocalDate plusDateByType(LocalDate localDate, PartitionType partitionType) {
86
+        switch (partitionType) {
87
+            case DAY:
88
+                return localDate.plusDays(1L);
89
+            case MONTH:
90
+                LocalDate date = localDate.plusMonths(1L);
91
+                return date.minusDays(date.getDayOfMonth() - 1);
92
+            default:
93
+                break;
94
+        }
95
+        throw new RuntimeException(partitionType.name());
96
+    }
97
+}

+ 32 - 0
src/main/java/com/vcarecity/cvs/MySQLCSVWriter.java 查看文件

@@ -0,0 +1,32 @@
1
+package com.vcarecity.cvs;
2
+
3
+import com.google.inject.Guice;
4
+import com.google.inject.Injector;
5
+import com.vcarecity.cvs.module.MySQLModule;
6
+import com.vcarecity.cvs.module.PropertiesModule;
7
+import com.vcarecity.cvs.properties.AppProperties;
8
+import me.yuxiaoyao.config.loader.ConfigLoader;
9
+import org.slf4j.Logger;
10
+import org.slf4j.LoggerFactory;
11
+
12
+/**
13
+ * @author Kerry on 19/11/20
14
+ */
15
+
16
+public class MySQLCSVWriter {
17
+    private static Logger logger = LoggerFactory.getLogger(MySQLCSVWriter.class);
18
+    public static Injector injector;
19
+
20
+    public static void main(String[] args) throws Exception {
21
+        final AppProperties appProperties = ConfigLoader.parseConfig(args, AppProperties.class, null);
22
+        injector = Guice.createInjector(new PropertiesModule(appProperties), new MySQLModule());
23
+
24
+        //final TestInsertData testInsertData = injector.getInstance(TestInsertData.class);
25
+        //testInsertData.ins();
26
+
27
+        final MySQLStarter instance = injector.getInstance(MySQLStarter.class);
28
+        instance.run();
29
+
30
+
31
+    }
32
+}

+ 70 - 0
src/main/java/com/vcarecity/cvs/MySQLStarter.java 查看文件

@@ -0,0 +1,70 @@
1
+package com.vcarecity.cvs;
2
+
3
+import com.vcarecity.cvs.entity.CheckRecordEntity;
4
+import com.vcarecity.cvs.factory.ResultHandlerFactory;
5
+import com.vcarecity.cvs.properties.AppProperties;
6
+import com.vcarecity.cvs.service.ResultHandlerService;
7
+import com.vcarecity.cvs.service.SQLQueryService;
8
+import com.vcarecity.cvs.service.impl.CSVResultHandlerServiceImpl;
9
+import lombok.extern.slf4j.Slf4j;
10
+
11
+import javax.inject.Inject;
12
+import java.util.List;
13
+
14
+/**
15
+ * @author Kerry on 19/11/20
16
+ */
17
+
18
+@Slf4j
19
+public class MySQLStarter {
20
+    private final AppProperties properties;
21
+    private final SQLQueryService queryService;
22
+    private final ResultHandlerFactory resultHandlerFactory;
23
+
24
+    @Inject
25
+    public MySQLStarter(AppProperties properties,
26
+                        SQLQueryService queryService,
27
+                        ResultHandlerFactory resultHandlerFactory) {
28
+
29
+        this.properties = properties;
30
+        this.queryService = queryService;
31
+        this.resultHandlerFactory = resultHandlerFactory;
32
+
33
+    }
34
+
35
+    static final int PAGE_COUNT = 10000;
36
+
37
+    public void run() throws Exception {
38
+
39
+        logger.info("start query database...");
40
+
41
+        long startTime = System.currentTimeMillis();
42
+
43
+
44
+        String sql = "select * from T_CHECK_RECORD limit ?,?";
45
+        // sql = "SELECT * FROM websites  limit ?,?";
46
+
47
+        String properties = "check_record.csv";
48
+
49
+        int count = 0;
50
+        int currentSize;
51
+
52
+
53
+        ResultHandlerService resultHandler = resultHandlerFactory.createResultHandler(properties);
54
+
55
+        do {
56
+            List<CheckRecordEntity> result = queryService.queryByPage(sql, count, PAGE_COUNT, CheckRecordEntity.class);
57
+            resultHandler.resultHandler(result, CheckRecordEntity.class);
58
+            currentSize = result.size();
59
+            count += currentSize;
60
+
61
+        } while (currentSize == PAGE_COUNT);
62
+
63
+        if (resultHandler instanceof CSVResultHandlerServiceImpl) {
64
+            ((CSVResultHandlerServiceImpl) resultHandler).close();
65
+        }
66
+
67
+        logger.info("stop query database...{} /ms.", (System.currentTimeMillis() - startTime));
68
+    }
69
+
70
+}

+ 55 - 0
src/main/java/com/vcarecity/cvs/TestInsertData.java 查看文件

@@ -0,0 +1,55 @@
1
+package com.vcarecity.cvs;
2
+
3
+import com.google.inject.Inject;
4
+import com.zaxxer.hikari.HikariDataSource;
5
+
6
+import java.sql.Connection;
7
+import java.sql.Date;
8
+import java.sql.PreparedStatement;
9
+import java.sql.SQLException;
10
+
11
+/**
12
+ * @author Kerry on 19/11/25
13
+ */
14
+
15
+public class TestInsertData {
16
+
17
+    private final HikariDataSource dataSource;
18
+
19
+    @Inject
20
+    public TestInsertData(HikariDataSource dataSource) {
21
+        this.dataSource = dataSource;
22
+    }
23
+
24
+    public void ins() throws SQLException {
25
+        //language=SQL
26
+        String sql = "insert into T_CHECK_RECORD_2 (STAMP, USER_ID, CHECK_POINTS_ID, IS_NORMAL, IS_LATENT_DANGER,\n" +
27
+                "                              LATENT_DANGER_TYPE, LATENT_DANGER_DESC, UNDETECTED_NUM, LON, LAT, RULE_ID, IS_DEAL,\n" +
28
+                "                              STARTDATE, ENDDATE, VALID_CHECK, UPDATESTAMP)\n" +
29
+                "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
30
+
31
+        final Connection connection = dataSource.getConnection();
32
+        final PreparedStatement preparedStatement = connection.prepareStatement(sql);
33
+
34
+        preparedStatement.setDate(1, new Date(System.currentTimeMillis()));
35
+        preparedStatement.setInt(2, 2834);
36
+        preparedStatement.setInt(3, 21);
37
+        preparedStatement.setInt(4, 0);
38
+        preparedStatement.setInt(5, 8);
39
+        preparedStatement.setInt(6, 0);
40
+        preparedStatement.setString(7, "\t");
41
+        preparedStatement.setInt(8, 0);
42
+        preparedStatement.setDouble(9, 113.123456);
43
+        preparedStatement.setDouble(10, 22.123456);
44
+        preparedStatement.setInt(11, 0);
45
+        preparedStatement.setInt(12, 0);
46
+        preparedStatement.setDate(13, null);
47
+        preparedStatement.setDate(14, null);
48
+        preparedStatement.setInt(15, 0);
49
+        preparedStatement.setDate(16, new Date(System.currentTimeMillis() + 1000));
50
+
51
+        preparedStatement.execute();
52
+        preparedStatement.close();
53
+        connection.close();
54
+    }
55
+}

+ 73 - 0
src/main/java/com/vcarecity/cvs/core/AutoMapper.java 查看文件

@@ -0,0 +1,73 @@
1
+package com.vcarecity.cvs.core;
2
+
3
+import java.lang.reflect.Modifier;
4
+import java.sql.Date;
5
+import java.sql.ResultSet;
6
+import java.sql.SQLException;
7
+import java.sql.Timestamp;
8
+import java.time.LocalDate;
9
+import java.time.LocalDateTime;
10
+import java.time.LocalTime;
11
+import java.util.List;
12
+
13
+/**
14
+ * @author Kerry on 19/11/21
15
+ */
16
+
17
+public class AutoMapper {
18
+
19
+
20
+    public static <T> T autoMapper(ResultSet resultSet, Class<T> cls) {
21
+        List<JavaMapColumn> fieldColumnList = ReflectionUtil.getFieldColumnList(cls);
22
+        try {
23
+            final T t = cls.newInstance();
24
+            for (JavaMapColumn fc : fieldColumnList) {
25
+                if (Modifier.isPrivate(fc.getField().getModifiers())) {
26
+                    fc.getField().setAccessible(true);
27
+                }
28
+                Class<?> type = fc.getField().getType();
29
+                Object object;
30
+                if (type == java.util.Date.class) {
31
+                    Timestamp timestamp = resultSet.getTimestamp(fc.getColumn());
32
+                    object = Date.from(timestamp.toInstant());
33
+                } else if (type == LocalDateTime.class) {
34
+                    Timestamp timestamp = resultSet.getTimestamp(fc.getColumn());
35
+                    object = timestamp.toLocalDateTime();
36
+                } else if (type == LocalDate.class) {
37
+                    Timestamp timestamp = resultSet.getTimestamp(fc.getColumn());
38
+                    object = timestamp.toLocalDateTime().toLocalDate();
39
+                } else if (type == LocalTime.class) {
40
+                    Timestamp timestamp = resultSet.getTimestamp(fc.getColumn());
41
+                    object = timestamp.toLocalDateTime().toLocalTime();
42
+                } else {
43
+                    // Timestamp 时出现 HOUR_OF_DAY 2->3 异常.请在mysql url 中加入 &serverTimezone=Asia/Shanghai
44
+                    object = resultSet.getObject(fc.getColumn(), type);
45
+                }
46
+                fc.getField().set(t, object);
47
+
48
+            }
49
+            return t;
50
+        } catch (InstantiationException | IllegalAccessException | SQLException e) {
51
+            e.printStackTrace();
52
+        }
53
+        return null;
54
+    }
55
+
56
+
57
+    public static <T> Object[] autoMapper(T t, Class<T> cls) {
58
+        List<JavaMapColumn> fieldColumnList = ReflectionUtil.getFieldColumnList(cls);
59
+        Object[] contents = new Object[fieldColumnList.size()];
60
+        try {
61
+            for (int i = 0; i < fieldColumnList.size(); i++) {
62
+                final JavaMapColumn fc = fieldColumnList.get(i);
63
+                if (Modifier.isPrivate(fc.getField().getModifiers())) {
64
+                    fc.getField().setAccessible(true);
65
+                }
66
+                contents[i] = fc.getField().get(t);
67
+            }
68
+        } catch (IllegalAccessException e) {
69
+            e.printStackTrace();
70
+        }
71
+        return contents;
72
+    }
73
+}

+ 15 - 0
src/main/java/com/vcarecity/cvs/core/JavaMapColumn.java 查看文件

@@ -0,0 +1,15 @@
1
+package com.vcarecity.cvs.core;
2
+
3
+import lombok.Data;
4
+
5
+import java.lang.reflect.Field;
6
+
7
+/**
8
+ * @author Kerry on 19/11/21
9
+ */
10
+
11
+@Data
12
+public class JavaMapColumn {
13
+    private final Field field;
14
+    private final String column;
15
+}

+ 51 - 0
src/main/java/com/vcarecity/cvs/core/ReflectionUtil.java 查看文件

@@ -0,0 +1,51 @@
1
+package com.vcarecity.cvs.core;
2
+
3
+import javax.persistence.Column;
4
+import javax.persistence.Transient;
5
+import java.lang.reflect.Field;
6
+import java.util.ArrayList;
7
+import java.util.List;
8
+import java.util.Map;
9
+import java.util.concurrent.ConcurrentHashMap;
10
+
11
+/**
12
+ * @author Kerry on 19/11/21
13
+ */
14
+
15
+public class ReflectionUtil {
16
+
17
+
18
+    private static final Map<Class<?>, List<JavaMapColumn>> FIELD_CACHE = new ConcurrentHashMap<>();
19
+
20
+
21
+    public static List<JavaMapColumn> getFieldColumnList(Class<?> cls) {
22
+
23
+        List<JavaMapColumn> fields = FIELD_CACHE.get(cls);
24
+        if (fields != null) {
25
+            return fields;
26
+        }
27
+        synchronized (FIELD_CACHE) {
28
+            Field[] declaredFields = cls.getDeclaredFields();
29
+            fields = new ArrayList<>(declaredFields.length);
30
+
31
+            for (Field declaredField : declaredFields) {
32
+                Transient ta = declaredField.getAnnotation(Transient.class);
33
+                if (ta != null) {
34
+                    continue;
35
+                }
36
+                final Column column = declaredField.getAnnotation(Column.class);
37
+                String fieldName = declaredField.getName();
38
+                if (column != null) {
39
+                    final String name = column.name();
40
+                    if (name.length() > 0) {
41
+                        fieldName = name;
42
+                    }
43
+                }
44
+                fields.add(new JavaMapColumn(declaredField, fieldName));
45
+            }
46
+            FIELD_CACHE.put(cls, fields);
47
+            return FIELD_CACHE.get(cls);
48
+        }
49
+    }
50
+
51
+}

+ 137 - 0
src/main/java/com/vcarecity/cvs/csv/DataBuilder.java 查看文件

@@ -0,0 +1,137 @@
1
+package com.vcarecity.cvs.csv;
2
+
3
+import java.io.IOException;
4
+import java.io.UnsupportedEncodingException;
5
+import java.time.LocalDateTime;
6
+import java.time.format.DateTimeFormatter;
7
+import java.util.Random;
8
+
9
+/**
10
+ * @author Kerry on 19/11/21
11
+ */
12
+
13
+public class DataBuilder {
14
+
15
+    public static void main(String[] args) throws IOException {
16
+        DataBuilder builder = new DataBuilder();
17
+        builder.builder();
18
+    }
19
+
20
+    public void builder() throws IOException {
21
+        int count = 1000000;
22
+        dateTime = LocalDateTime.of(2018, 1, 1, 0, 0, 0);
23
+
24
+        String[] header = {
25
+                "CHECK_RECORD_ID",
26
+                "STAMP",
27
+                "USER_ID",
28
+                "CHECK_POINTS_ID",
29
+                "IS_NORMAL",
30
+                "IS_LATENT_DANGER",
31
+                "LATENT_DANGER_TYPE",
32
+                "LATENT_DANGER_DESC",
33
+                "UNDETECTED_NUM",
34
+                "LON",
35
+                "LAT",
36
+                "RULE_ID",
37
+                "IS_DEAL",
38
+                "STARTDATE",
39
+                "ENDDATE",
40
+                "VALID_CHECK",
41
+                "UPDATESTAMP"
42
+        };
43
+
44
+
45
+    }
46
+
47
+    public static final String NULL_VALUE = "\\N";
48
+
49
+    private final int min_user_id = 2000;
50
+    private Random random = new Random();
51
+    private long recordId = 1;
52
+    private LocalDateTime dateTime;
53
+    private int userId = min_user_id;
54
+
55
+
56
+    private String[] getContent(int index, int col) {
57
+        index++;
58
+        String[] line = new String[col];
59
+        line[0] = "" + (recordId++);
60
+        if (index % 1500 == 0) {
61
+            dateTime = dateTime.plusDays(1L);
62
+        }
63
+        line[1] = formatDateTime(dateTime);
64
+        line[2] = getUserId();
65
+        line[3] = getUserId();
66
+        line[4] = String.valueOf(random.nextInt(10));
67
+        line[5] = String.valueOf(random.nextInt(10));
68
+        line[6] = String.valueOf(random.nextInt(10));
69
+
70
+        line[7] = getMessage();
71
+
72
+        line[8] = String.valueOf(random.nextInt(55555));
73
+        line[9] = "" + Math.random() * 100;
74
+        line[10] = "" + Math.random() * 100;
75
+        line[11] = String.valueOf(random.nextInt(100000));
76
+        line[12] = String.valueOf(random.nextInt(12));
77
+        line[13] = null;
78
+        line[14] = null;
79
+        line[15] = String.valueOf(random.nextInt(12));
80
+        line[16] = formatDateTime(dateTime);
81
+
82
+        for (int i = 0; i < line.length; i++) {
83
+            if (line[i] == null) {
84
+                line[i] = NULL_VALUE;
85
+            }
86
+        }
87
+
88
+        return line;
89
+    }
90
+
91
+    private String getUserId() {
92
+        int max_user_id = 20000;
93
+        if (userId > max_user_id) {
94
+            userId = min_user_id;
95
+        }
96
+        return String.valueOf(userId++);
97
+    }
98
+
99
+    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
100
+
101
+    private static String formatDateTime(LocalDateTime localDateTime) {
102
+        return localDateTime.format(FORMATTER);
103
+    }
104
+
105
+    public String getMessage() {
106
+        final int i = random.nextInt(60);
107
+        StringBuffer sb = new StringBuffer();
108
+        for (int j = 0; j < i; j++) {
109
+            sb.append(getRandomChar());
110
+        }
111
+        return sb.toString();
112
+    }
113
+
114
+    public static String getRandomChar() {
115
+        String str = "";
116
+        int highCode;
117
+        int lowCode;
118
+
119
+        Random random = new Random();
120
+        //B0 + 0~39(16~55) 一级汉字所占区
121
+        highCode = (176 + Math.abs(random.nextInt(39)));
122
+        //A1 + 0~93 每区有94个汉字
123
+        lowCode = (161 + Math.abs(random.nextInt(93)));
124
+
125
+        byte[] b = new byte[2];
126
+        b[0] = (Integer.valueOf(highCode)).byteValue();
127
+        b[1] = (Integer.valueOf(lowCode)).byteValue();
128
+
129
+        try {
130
+            str = new String(b, "GBK");
131
+        } catch (UnsupportedEncodingException e) {
132
+            e.printStackTrace();
133
+        }
134
+        return str;
135
+    }
136
+
137
+}

+ 13 - 0
src/main/java/com/vcarecity/cvs/csv/SQLCSVWriter.java 查看文件

@@ -0,0 +1,13 @@
1
+package com.vcarecity.cvs.csv;
2
+
3
+
4
+
5
+/**
6
+ * @author Kerry on 19/11/21
7
+ */
8
+
9
+public class SQLCSVWriter {
10
+
11
+
12
+
13
+}

+ 68 - 0
src/main/java/com/vcarecity/cvs/entity/CheckRecordEntity.java 查看文件

@@ -0,0 +1,68 @@
1
+package com.vcarecity.cvs.entity;
2
+
3
+import lombok.Data;
4
+
5
+import javax.persistence.Column;
6
+import java.sql.Timestamp;
7
+
8
+
9
+/**
10
+ * @author Kerry on 19/11/21
11
+ */
12
+
13
+@Data
14
+public class CheckRecordEntity {
15
+
16
+    @Column(name = "CHECK_RECORD_ID")
17
+    private Long checkRecordId;
18
+
19
+    @Column(name = "STAMP")
20
+    private Timestamp stamp;
21
+
22
+    @Column(name = "USER_ID")
23
+    private Long userId;
24
+
25
+    @Column(name = "CHECK_POINTS_ID")
26
+    private Long checkPointsId;
27
+
28
+    @Column(name = "IS_NORMAL")
29
+    private Integer isNormal;
30
+
31
+    @Column(name = "IS_LATENT_DANGER")
32
+    private Integer isLatentDanger;
33
+
34
+    @Column(name = "LATENT_DANGER_TYPE")
35
+    private Integer latentDangerType;
36
+
37
+    @Column(name = "LATENT_DANGER_DESC")
38
+    private String latentDangerDesc;
39
+
40
+    @Column(name = "UNDETECTED_NUM")
41
+    private String undetectedNum;
42
+
43
+    @Column(name = "LON")
44
+    private Double lon;
45
+
46
+    @Column(name = "LAT")
47
+    private Double lat;
48
+
49
+    @Column(name = "RULE_ID")
50
+    private Long ruleId;
51
+
52
+    @Column(name = "IS_DEAL")
53
+    private Integer isDeal;
54
+
55
+    @Column(name = "STARTDATE")
56
+    private String startDate;
57
+
58
+    @Column(name = "ENDDATE")
59
+    private String endDate;
60
+
61
+    @Column(name = "VALID_CHECK")
62
+    private Integer validCheck;
63
+
64
+    @Column(name = "UPDATESTAMP")
65
+    private Timestamp updateStamp;
66
+
67
+
68
+}

+ 18 - 0
src/main/java/com/vcarecity/cvs/entity/WebSiteEntity.java 查看文件

@@ -0,0 +1,18 @@
1
+package com.vcarecity.cvs.entity;
2
+
3
+import lombok.Data;
4
+
5
+/**
6
+ * @author Kerry on 19/11/22
7
+ */
8
+
9
+@Data
10
+public class WebSiteEntity {
11
+    private Integer id;
12
+    private String name;
13
+    private String url;
14
+    private Integer alexa;
15
+    private String country;
16
+    private String tm;
17
+    private Integer ti;
18
+}

+ 19 - 0
src/main/java/com/vcarecity/cvs/factory/ResultHandlerFactory.java 查看文件

@@ -0,0 +1,19 @@
1
+package com.vcarecity.cvs.factory;
2
+
3
+import com.vcarecity.cvs.service.ResultHandlerService;
4
+
5
+/**
6
+ * @author Kerry on 19/11/21
7
+ */
8
+
9
+public interface ResultHandlerFactory {
10
+
11
+    /**
12
+     * create
13
+     *
14
+     * @param properties
15
+     * @return
16
+     */
17
+    ResultHandlerService createResultHandler(String properties);
18
+
19
+}

+ 60 - 0
src/main/java/com/vcarecity/cvs/module/MySQLModule.java 查看文件

@@ -0,0 +1,60 @@
1
+package com.vcarecity.cvs.module;
2
+
3
+import com.google.inject.AbstractModule;
4
+import com.google.inject.Inject;
5
+import com.google.inject.Provides;
6
+import com.google.inject.Singleton;
7
+import com.google.inject.assistedinject.FactoryModuleBuilder;
8
+import com.vcarecity.cvs.factory.ResultHandlerFactory;
9
+import com.vcarecity.cvs.properties.AppProperties;
10
+import com.vcarecity.cvs.properties.DbProperties;
11
+import com.vcarecity.cvs.service.ResultHandlerService;
12
+import com.vcarecity.cvs.service.SQLQueryService;
13
+import com.vcarecity.cvs.service.impl.CSVResultHandlerServiceImpl;
14
+import com.vcarecity.cvs.service.impl.MySQLQueryServiceImpl;
15
+import com.zaxxer.hikari.HikariConfig;
16
+import com.zaxxer.hikari.HikariDataSource;
17
+
18
+/**
19
+ * @author Kerry on 19/11/20
20
+ */
21
+
22
+public class MySQLModule extends AbstractModule {
23
+    @Override
24
+    protected void configure() {
25
+        bind(SQLQueryService.class).to(MySQLQueryServiceImpl.class);
26
+
27
+        install(new FactoryModuleBuilder()
28
+                .implement(ResultHandlerService.class, CSVResultHandlerServiceImpl.class)
29
+                .build(ResultHandlerFactory.class));
30
+
31
+    }
32
+
33
+    @Provides
34
+    @Singleton
35
+    @Inject
36
+    public HikariDataSource dataSource(AppProperties properties) {
37
+        // @see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
38
+
39
+        final DbProperties database = properties.getDatabase();
40
+        HikariConfig config = new HikariConfig();
41
+        config.setJdbcUrl(database.getUrl());
42
+        config.setUsername(database.getUser());
43
+        config.setPassword(database.getPassword());
44
+        config.addDataSourceProperty("cachePrepStmts", "true");
45
+        config.addDataSourceProperty("prepStmtCacheSize", "250");
46
+        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
47
+        config.addDataSourceProperty("useServerPrepStmts", "true");
48
+        config.addDataSourceProperty("useLocalSessionState", "true");
49
+        config.addDataSourceProperty("rewriteBatchedStatements", "true");
50
+        config.addDataSourceProperty("cacheResultSetMetadata", "true");
51
+        config.addDataSourceProperty("cacheServerConfiguration", "true");
52
+        config.addDataSourceProperty("elideSetAutoCommits", "true");
53
+        config.addDataSourceProperty("maintainTimeStats", "false");
54
+
55
+        final HikariDataSource hikariDataSource = new HikariDataSource(config);
56
+        Runtime.getRuntime().addShutdownHook(new Thread(hikariDataSource::close));
57
+        return hikariDataSource;
58
+    }
59
+
60
+}

+ 21 - 0
src/main/java/com/vcarecity/cvs/module/PropertiesModule.java 查看文件

@@ -0,0 +1,21 @@
1
+package com.vcarecity.cvs.module;
2
+
3
+import com.google.inject.AbstractModule;
4
+import com.vcarecity.cvs.properties.AppProperties;
5
+
6
+/**
7
+ * @author Kerry on 19/11/20
8
+ */
9
+
10
+public class PropertiesModule extends AbstractModule {
11
+    private final AppProperties properties;
12
+
13
+    public PropertiesModule(AppProperties properties) {
14
+        this.properties = properties;
15
+    }
16
+
17
+    @Override
18
+    protected void configure() {
19
+        bind(AppProperties.class).toInstance(this.properties);
20
+    }
21
+}

+ 12 - 0
src/main/java/com/vcarecity/cvs/properties/AppProperties.java 查看文件

@@ -0,0 +1,12 @@
1
+package com.vcarecity.cvs.properties;
2
+
3
+import lombok.Data;
4
+
5
+/**
6
+ * @author Kerry on 19/11/20
7
+ */
8
+
9
+@Data
10
+public class AppProperties {
11
+    private DbProperties database;
12
+}

+ 14 - 0
src/main/java/com/vcarecity/cvs/properties/DbProperties.java 查看文件

@@ -0,0 +1,14 @@
1
+package com.vcarecity.cvs.properties;
2
+
3
+import lombok.Data;
4
+
5
+/**
6
+ * @author Kerry on 19/11/20
7
+ */
8
+
9
+@Data
10
+public class DbProperties {
11
+    private String url;
12
+    private String user;
13
+    private String password;
14
+}

+ 22 - 0
src/main/java/com/vcarecity/cvs/service/ResultHandlerService.java 查看文件

@@ -0,0 +1,22 @@
1
+package com.vcarecity.cvs.service;
2
+
3
+import java.util.List;
4
+
5
+/**
6
+ * @author Kerry on 19/11/21
7
+ */
8
+
9
+public interface ResultHandlerService {
10
+
11
+
12
+    /**
13
+     * ins
14
+     *
15
+     * @param dataList
16
+     * @param cls
17
+     * @throws Exception
18
+     */
19
+    <T> void resultHandler(List<T> dataList, Class<T> cls) throws Exception;
20
+
21
+
22
+}

+ 27 - 0
src/main/java/com/vcarecity/cvs/service/SQLQueryService.java 查看文件

@@ -0,0 +1,27 @@
1
+package com.vcarecity.cvs.service;
2
+
3
+import java.sql.SQLException;
4
+import java.util.List;
5
+
6
+/**
7
+ * @author Kerry on 19/11/21
8
+ */
9
+
10
+public interface SQLQueryService {
11
+
12
+
13
+    /**
14
+     * query by page
15
+     *
16
+     * @param sql
17
+     * @param start
18
+     * @param pageCount
19
+     * @param clazz
20
+     * @param <T>
21
+     * @return
22
+     * @throws SQLException
23
+     */
24
+    <T> List<T> queryByPage(String sql, int start, int pageCount, Class<T> clazz) throws SQLException;
25
+
26
+
27
+}

+ 188 - 0
src/main/java/com/vcarecity/cvs/service/impl/CSVResultHandlerServiceImpl.java 查看文件

@@ -0,0 +1,188 @@
1
+package com.vcarecity.cvs.service.impl;
2
+
3
+
4
+import com.google.inject.Inject;
5
+import com.google.inject.assistedinject.Assisted;
6
+import com.vcarecity.cvs.core.AutoMapper;
7
+import com.vcarecity.cvs.core.JavaMapColumn;
8
+import com.vcarecity.cvs.core.ReflectionUtil;
9
+import com.vcarecity.cvs.service.ResultHandlerService;
10
+import lombok.extern.slf4j.Slf4j;
11
+import org.apache.commons.csv.CSVFormat;
12
+import org.apache.commons.csv.CSVPrinter;
13
+
14
+import java.io.BufferedWriter;
15
+import java.io.File;
16
+import java.io.IOException;
17
+import java.nio.file.Files;
18
+import java.sql.Timestamp;
19
+import java.time.*;
20
+import java.time.format.DateTimeFormatter;
21
+import java.util.List;
22
+import java.util.stream.Collectors;
23
+
24
+/**
25
+ * @author Kerry on 19/11/21
26
+ */
27
+
28
+@Slf4j
29
+public class CSVResultHandlerServiceImpl implements ResultHandlerService {
30
+
31
+    private final CSVFormat csvFormat;
32
+
33
+    private BufferedWriter bufferedWriter = null;
34
+    private CSVPrinter writer = null;
35
+
36
+    private final String filePattern;
37
+    private int counter;
38
+    private int fileNameIndex = 0;
39
+
40
+
41
+    /**
42
+     * 分割文件行数
43
+     */
44
+    private static final int SPLIT_LINE_NUM = 200_0000;
45
+
46
+
47
+    @Inject
48
+    public CSVResultHandlerServiceImpl(@Assisted String filePattern) {
49
+        this.filePattern = filePattern;
50
+        this.csvFormat = CSVFormat.MYSQL;
51
+        this.counter = 0;
52
+    }
53
+
54
+    private File getFile() {
55
+        final int index = fileNameIndex;
56
+        fileNameIndex++;
57
+        return new File(filePattern + index + ".csv");
58
+    }
59
+
60
+
61
+    private void checkFile() {
62
+        synchronized (this) {
63
+            if (counter % SPLIT_LINE_NUM == 0) {
64
+                try {
65
+                    if (bufferedWriter != null) {
66
+                        bufferedWriter.close();
67
+                    }
68
+                    if (writer != null) {
69
+                        writer.close();
70
+                    }
71
+                    bufferedWriter = Files.newBufferedWriter(getFile().toPath());
72
+                    writer = new CSVPrinter(bufferedWriter, csvFormat);
73
+                } catch (IOException e) {
74
+                    e.printStackTrace();
75
+                }
76
+            }
77
+        }
78
+    }
79
+
80
+    @Override
81
+    public <T> void resultHandler(List<T> dataList, Class<T> cls) throws Exception {
82
+        checkFile();
83
+
84
+        logger.debug("start write to csv file size = {}", dataList.size());
85
+
86
+        long startTime = System.currentTimeMillis();
87
+
88
+        for (T t : dataList) {
89
+            Object[] row;
90
+            if (cls.isArray()) {
91
+                // array
92
+                row = (Object[]) t;
93
+            } else if (List.class.isAssignableFrom(cls)) {
94
+                // noinspection rawtypes
95
+                row = ((List) t).toArray();
96
+            } else {
97
+                row = resultMapper(t, cls);
98
+            }
99
+            Object[] handlerRow = toCsvContent(row);
100
+            writer.printRecord(handlerRow);
101
+        }
102
+        bufferedWriter.flush();
103
+
104
+        counter += dataList.size();
105
+
106
+
107
+        // 输出Header
108
+        final List<JavaMapColumn> fieldColumnList = ReflectionUtil.getFieldColumnList(cls);
109
+        final List<String> collect = fieldColumnList.stream().map(JavaMapColumn::getColumn).collect(Collectors.toList());
110
+        final String join = String.join(",", collect.toArray(new String[]{}));
111
+
112
+        logger.debug("write to csv file usage time {} /ms. header = ({})", (System.currentTimeMillis() - startTime), join);
113
+    }
114
+
115
+
116
+    protected <T> Object[] resultMapper(T t, Class<T> cls) {
117
+        return AutoMapper.autoMapper(t, cls);
118
+    }
119
+
120
+    public void close() throws IOException {
121
+        bufferedWriter.close();
122
+        writer.close();
123
+    }
124
+
125
+    private static Object[] toCsvContent(Object[] objects) {
126
+        Object[] contents = new Object[objects.length];
127
+
128
+        // 主要是对 时间格式的处理
129
+
130
+        for (int i = 0; i < objects.length; i++) {
131
+            final Object object = objects[i];
132
+            if (object == null) {
133
+                contents[i] = null;
134
+            } else if (object instanceof Timestamp) {
135
+                contents[i] = formatTimestamp((Timestamp) object);
136
+            } else if (object instanceof java.sql.Date) {
137
+                contents[i] = formatDate((java.sql.Date) object);
138
+            } else if (object instanceof java.util.Date) {
139
+                contents[i] = formatDate((java.util.Date) object);
140
+            } else if (object instanceof LocalDateTime) {
141
+                contents[i] = formatLocalDateTime((LocalDateTime) object);
142
+            } else if (object instanceof LocalDate) {
143
+                contents[i] = formatLocalDate((LocalDate) object);
144
+            } else if (object instanceof LocalTime) {
145
+                contents[i] = formatLocalTime((LocalTime) object);
146
+            } else {
147
+                contents[i] = object;
148
+            }
149
+        }
150
+        return contents;
151
+    }
152
+
153
+    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
154
+
155
+    private static String formatLocalDate(LocalDate localDate) {
156
+        return localDate.format(DATE_FORMATTER);
157
+    }
158
+
159
+
160
+    private static String formatDate(java.sql.Date date) {
161
+        final LocalDate localDate = date.toLocalDate();
162
+        return localDate.format(DATE_FORMATTER);
163
+    }
164
+
165
+    private static String formatDate(java.util.Date date) {
166
+        final Instant instant = date.toInstant();
167
+        final LocalDateTime of = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
168
+        return of.format(DATE_TIME_FORMATTER);
169
+    }
170
+
171
+    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
172
+
173
+    private static String formatTimestamp(Timestamp timestamp) {
174
+        final LocalDateTime localDateTime = timestamp.toLocalDateTime();
175
+        return localDateTime.format(DATE_TIME_FORMATTER);
176
+    }
177
+
178
+    private static String formatLocalDateTime(LocalDateTime localDateTime) {
179
+        return localDateTime.format(DATE_TIME_FORMATTER);
180
+    }
181
+
182
+    public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
183
+
184
+    private static String formatLocalTime(LocalTime localTime) {
185
+        return localTime.format(TIME_FORMATTER);
186
+    }
187
+
188
+}

+ 56 - 0
src/main/java/com/vcarecity/cvs/service/impl/MySQLQueryServiceImpl.java 查看文件

@@ -0,0 +1,56 @@
1
+package com.vcarecity.cvs.service.impl;
2
+
3
+import com.google.inject.Inject;
4
+import com.vcarecity.cvs.core.AutoMapper;
5
+import com.vcarecity.cvs.service.SQLQueryService;
6
+import com.zaxxer.hikari.HikariDataSource;
7
+import lombok.extern.slf4j.Slf4j;
8
+
9
+import java.sql.Connection;
10
+import java.sql.PreparedStatement;
11
+import java.sql.ResultSet;
12
+import java.sql.SQLException;
13
+import java.util.ArrayList;
14
+import java.util.List;
15
+
16
+/**
17
+ * @author Kerry on 19/11/21
18
+ */
19
+
20
+
21
+@Slf4j
22
+public class MySQLQueryServiceImpl implements SQLQueryService {
23
+    private final HikariDataSource dataSource;
24
+
25
+    @Inject
26
+    public MySQLQueryServiceImpl(HikariDataSource dataSource) {
27
+        this.dataSource = dataSource;
28
+    }
29
+
30
+    @Override
31
+    public <T> List<T> queryByPage(String sql, int start, int pageCount, Class<T> clazz) throws SQLException {
32
+        final Connection connection = dataSource.getConnection();
33
+        final PreparedStatement preparedStatement = connection.prepareStatement(sql);
34
+        preparedStatement.setInt(1, start);
35
+        preparedStatement.setInt(2, pageCount);
36
+
37
+        List<T> list = new ArrayList<>(pageCount);
38
+        long startTime = System.currentTimeMillis();
39
+
40
+        logger.debug("start query: {},{},{}.start on = {}", sql, start, pageCount, startTime);
41
+
42
+        final ResultSet resultSet = preparedStatement.executeQuery();
43
+        while (resultSet.next()) {
44
+            // mapper
45
+            final T t = AutoMapper.autoMapper(resultSet, clazz);
46
+            if (t != null) {
47
+                list.add(t);
48
+            }
49
+        }
50
+
51
+        logger.debug("start query: {},{},{}.usageTime= {}", sql, start, pageCount, (System.currentTimeMillis() - startTime));
52
+        connection.close();
53
+
54
+        return list;
55
+    }
56
+}

+ 42 - 0
src/main/java/com/vcarecity/cvs/service/impl/MySQLResultHandlerServiceImpl.java 查看文件

@@ -0,0 +1,42 @@
1
+package com.vcarecity.cvs.service.impl;
2
+
3
+import com.google.inject.Inject;
4
+import com.google.inject.assistedinject.Assisted;
5
+import com.vcarecity.cvs.service.ResultHandlerService;
6
+import com.zaxxer.hikari.HikariDataSource;
7
+import lombok.extern.slf4j.Slf4j;
8
+
9
+import java.sql.Connection;
10
+import java.time.LocalDateTime;
11
+import java.util.List;
12
+
13
+/**
14
+ * @author Kerry on 19/11/21
15
+ */
16
+
17
+
18
+@Slf4j
19
+public class MySQLResultHandlerServiceImpl implements ResultHandlerService {
20
+
21
+    private final HikariDataSource dataSource;
22
+    private final String sql;
23
+
24
+    @Inject
25
+    public MySQLResultHandlerServiceImpl(HikariDataSource dataSource, @Assisted String sql) {
26
+        this.dataSource = dataSource;
27
+        this.sql = sql;
28
+    }
29
+
30
+
31
+    @Override
32
+    public <T> void resultHandler(List<T> dataList, Class<T> cls) throws Exception {
33
+        logger.debug("start write to mysql size = {}, on = {}", dataList.size(), LocalDateTime.now());
34
+        long startTime = System.currentTimeMillis();
35
+        final Connection connection = dataSource.getConnection();
36
+
37
+
38
+        connection.close();
39
+
40
+        logger.debug("write to mysql usage time {} /ms", System.currentTimeMillis() - startTime);
41
+    }
42
+}

+ 55 - 0
src/main/java/com/vcarecity/cvs/service/impl/OracleQueryServiceImpl.java 查看文件

@@ -0,0 +1,55 @@
1
+package com.vcarecity.cvs.service.impl;
2
+
3
+import com.google.inject.Inject;
4
+import com.vcarecity.cvs.core.AutoMapper;
5
+import com.vcarecity.cvs.service.SQLQueryService;
6
+import com.zaxxer.hikari.HikariDataSource;
7
+import lombok.extern.slf4j.Slf4j;
8
+
9
+import java.sql.Connection;
10
+import java.sql.PreparedStatement;
11
+import java.sql.ResultSet;
12
+import java.sql.SQLException;
13
+import java.util.ArrayList;
14
+import java.util.List;
15
+
16
+/**
17
+ * @author Kerry on 19/11/25
18
+ */
19
+
20
+@Slf4j
21
+public class OracleQueryServiceImpl implements SQLQueryService {
22
+    private final HikariDataSource dataSource;
23
+
24
+    @Inject
25
+    public OracleQueryServiceImpl(HikariDataSource dataSource) {
26
+        this.dataSource = dataSource;
27
+    }
28
+
29
+    @Override
30
+    public <T> List<T> queryByPage(String sql, int start, int pageCount, Class<T> clazz) throws SQLException {
31
+        final Connection connection = dataSource.getConnection();
32
+        final PreparedStatement preparedStatement = connection.prepareStatement(sql);
33
+        preparedStatement.setInt(1, start);
34
+        preparedStatement.setInt(2, pageCount);
35
+
36
+        List<T> list = new ArrayList<>(pageCount);
37
+        long startTime = System.currentTimeMillis();
38
+
39
+        logger.debug("start query: {},{},{}.start on = {}", sql, start, pageCount, startTime);
40
+
41
+        final ResultSet resultSet = preparedStatement.executeQuery();
42
+        while (resultSet.next()) {
43
+            // mapper
44
+            final T t = AutoMapper.autoMapper(resultSet, clazz);
45
+            if (t != null) {
46
+                list.add(t);
47
+            }
48
+        }
49
+
50
+        logger.debug("start query: {},{},{}.usageTime= {}", sql, start, pageCount, (System.currentTimeMillis() - startTime));
51
+        connection.close();
52
+
53
+        return list;
54
+    }
55
+}

+ 1 - 0
src/main/lombok.config 查看文件

@@ -0,0 +1 @@
1
+lombok.log.fieldName = logger

+ 38 - 0
src/main/resources/logback-test.xml 查看文件

@@ -0,0 +1,38 @@
1
+<configuration scan="true" scanPeriod="120 seconds">
2
+
3
+    <property name="LOG_HOME" value="./logs"/>
4
+    <statusListener class="ch.qos.logback.core.status.NopStatusListener"/>
5
+
6
+    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
7
+        <encoder>
8
+            <pattern>%d{yyyy-MM-dd HH:mm:ss} %highlight(%-5level) [%15.15t] %cyan(%-40.40logger{39}): %msg %n</pattern>
9
+        </encoder>
10
+    </appender>
11
+
12
+    <appender name="FILE_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
13
+
14
+        <file>${LOG_HOME}/application.log</file>
15
+        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
16
+            <fileNamePattern>${LOG_HOME}/application.%d{yyyyMMdd}_%i.log</fileNamePattern>
17
+            <maxHistory>30</maxHistory>
18
+            <totalSizeCap>20GB</totalSizeCap>
19
+            <maxFileSize>50MB</maxFileSize>
20
+        </rollingPolicy>
21
+        <encoder>
22
+            <pattern>%d{yy-MM-dd HH:mm:ss} %-5level [%15.15t] %-40.40logger{39}: %msg %n</pattern>
23
+        </encoder>
24
+    </appender>
25
+
26
+    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender" additivity="false">
27
+        <appender-ref ref="FILE_APPENDER"/>
28
+    </appender>
29
+
30
+    <logger name="com.vcarecity" level="DEBUG" additivity="false">
31
+        <appender-ref ref="STDOUT"/>
32
+    </logger>
33
+
34
+    <root level="INFO">
35
+        <appender-ref ref="STDOUT"/>
36
+    </root>
37
+
38
+</configuration>

+ 7 - 0
src/test/java/com/vcarecity/cvs/service/impl/CSVResultHandlerServiceImplTest.java 查看文件

@@ -0,0 +1,7 @@
1
+package com.vcarecity.cvs.service.impl;
2
+
3
+
4
+
5
+class CSVResultHandlerServiceImplTest {
6
+
7
+}

+ 1 - 0
src/test/lombok.config 查看文件

@@ -0,0 +1 @@
1
+lombok.log.fieldName = logger