ClickHouseUtils.java 10.2 KB
Newer Older
wang-jinfeng committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
package mobvista.dmp.datasource.baichuan;

import com.google.common.util.concurrent.ListenableFuture;
import ru.yandex.clickhouse.except.ClickHouseUnknownException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @package: mobvista.dmp.datasource.baichuan
 * @author: wangjf
 * @date: 2019-08-26
 * @time: 15:48
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class ClickHouseUtils {
    /**
     * @param appId  应用ID,1-tmail,2-taobao
     * @param appOs  设备ID类型,1-android,2-ios
     * @param offSet 偏移量
     * @param size   每页查询设备量
     * @return
     * @throws SQLException
     */
    public static ResultSet query(Connection connection, String dt, String appId, String appOs, int offSet, int size) throws SQLException, InterruptedException {
        ResultSet resultSet;
        String sql = "SELECT device_id FROM etl_baichuan_daily_all WHERE dt = '@dt' AND app_id = @appId AND app_os = @appOs AND tag = 0 LIMIT @offSet, @size";
        sql = sql.replace("@dt", dt)
                .replace("@appId", appId)
                .replace("@appOs", appOs).replace("@offSet", String.valueOf(offSet)).replace("@size", String.valueOf(size));
        try {
            resultSet = connection.createStatement().executeQuery(sql);
            return resultSet;
        } catch (ClickHouseUnknownException e) {
            Thread.sleep(200);
            resultSet = connection.createStatement().executeQuery(sql);
            return resultSet;
        }
    }

    public static ResultSet queryAli(Connection connection, String dt, String appId, String appOs, int offSet, int size) throws SQLException, InterruptedException {
        ResultSet resultSet;

        String sql = "SELECT device_id, app_os FROM dwh.etl_baichuan_daily_all WHERE dt ='@dt' AND app_id = @appId AND app_os = @appOs AND tag = 0 LIMIT @offSet, @size";

        sql = sql.replace("@dt", dt).replace("@appId", appId)
                .replace("@appOs", appOs).replace("@offSet", String.valueOf(offSet))
                .replace("@size", String.valueOf(size));
        try {
            resultSet = connection.createStatement().executeQuery(sql);
            return resultSet;
        } catch (ClickHouseUnknownException e) {
            Thread.sleep(200);
            resultSet = connection.createStatement().executeQuery(sql);
            return resultSet;
        }
    }

    public static ResultSet queryExcludeAli(Connection connection, String dt, int offSet, int size) throws SQLException, InterruptedException {
        ResultSet resultSet;

        String sql = "SELECT device_id, 2 app_os FROM baichuan_exclude_ios_daily_all WHERE dt ='@dt' LIMIT @offSet, @size";
        sql = sql.replace("@dt", dt)
                .replace("@offSet", String.valueOf(offSet)).replace("@size", String.valueOf(size));
        try {
            resultSet = connection.createStatement().executeQuery(sql);
            return resultSet;
        } catch (ClickHouseUnknownException e) {
            Thread.sleep(200);
            resultSet = connection.createStatement().executeQuery(sql);
            return resultSet;
        }
    }

    /**
     * @param asoDeviceSet 百川返回 is_new_device 为 false 的设备列表
     * @throws SQLException
     */
    public static void insert(Connection connection, AtomicReference<Set<AsoDevice>> asoDeviceSet) throws SQLException, InterruptedException, ConcurrentModificationException {
        PreparedStatement preparedStatement = null;
        try {
            /*
            String createSql = "CREATE TABLE IF NOT EXISTS dwh.baichuan_install_daily (dt Date, device_id String, device_type String, platform String, package_name String) ENGINE = MergeTree()" +
                    " PARTITION BY toYYYYMMDD(dt) ORDER BY (dt, device_id) SETTINGS index_granularity = 8192";
            connection.createStatement().execute(createSql);
            String createAllSql = "CREATE TABLE IF NOT EXISTS dwh.baichuan_install_daily_all (dt Date, device_id String, device_type String, platform String, package_name String) " +
                    "ENGINE = Distributed(cluster_1st,dwh,baichuan_install_daily,rand())";
            connection.createStatement().execute(createAllSql);
            */
            preparedStatement = connection.prepareStatement("INSERT INTO dwh.baichuan_install_daily (dt, device_id, device_type, platform, package_name) VALUES (?, ?, ?, ?, ?)");
            for (AsoDevice deviceInfo : asoDeviceSet.get()) {
                preparedStatement.setString(1, deviceInfo.getDt());
                preparedStatement.setString(2, deviceInfo.getDeviceId());
                preparedStatement.setString(3, deviceInfo.getDeviceType());
                preparedStatement.setString(4, deviceInfo.getPlatform());
                preparedStatement.setString(5, deviceInfo.getPackageName());
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
        } catch (ClickHouseUnknownException | NullPointerException e) {
            Thread.sleep(200);
            assert preparedStatement != null;
            preparedStatement.executeBatch();
        } finally {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        }
    }

    /**
     * @throws SQLException
     */
    public static void insert2(Connection connection, List<ListenableFuture<AsoDevice>> futures) throws SQLException, InterruptedException, ConcurrentModificationException {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement("INSERT INTO dwh.baichuan_install_daily (dt, device_id, device_type, platform, package_name) VALUES (?, ?, ?, ?, ?)");
            for (ListenableFuture<AsoDevice> future : futures) {
                try {
                    AsoDevice iQiYiClass = future.get();
                    preparedStatement.setString(1, iQiYiClass.getDt());
                    preparedStatement.setString(2, iQiYiClass.getDeviceId());
                    preparedStatement.setString(3, iQiYiClass.getDeviceType());
                    preparedStatement.setString(4, iQiYiClass.getPlatform());
                    preparedStatement.setString(5, iQiYiClass.getPackageName());
                    preparedStatement.addBatch();
                } catch (ExecutionException | NullPointerException e) {
                    //  NO
                }
            }
            preparedStatement.executeBatch();
        } catch (ClickHouseUnknownException | NullPointerException e) {
            Thread.sleep(200);
            assert preparedStatement != null;
            preparedStatement.executeBatch();
        } finally {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        }
    }

    public static void insert(Connection connection, Set<String> deviceSet, boolean isNewDevice) throws SQLException, InterruptedException {
        PreparedStatement preparedStatement = null;
        try {
            /*
            String createSql = "CREATE TABLE IF NOT EXISTS dwh.baichuan_install_daily (dt Date, device_id String, device_type String, platform String, package_name String) ENGINE = MergeTree()" +
                    " PARTITION BY toYYYYMMDD(dt) ORDER BY (dt, device_id) SETTINGS index_granularity = 8192";
            connection.createStatement().execute(createSql);
            String createAllSql = "CREATE TABLE IF NOT EXISTS dwh.baichuan_install_daily_all (dt Date, device_id String, device_type String, platform String, package_name String) " +
                    "ENGINE = Distributed(cluster_1st,dwh,baichuan_install_daily,rand())";
            connection.createStatement().execute(createAllSql);
            */
            preparedStatement = connection.prepareStatement("INSERT INTO dwh.baichuan_install_daily (dt, device_id, device_type, platform, package_name) VALUES (?, ?, ?, ?, ?)");
            for (String deviceInfo : deviceSet) {
                //  preparedStatement.setString(1, deviceInfo.getDt());
                //  preparedStatement.setString(2, deviceInfo.getDeviceId());
                //  preparedStatement.setString(3, deviceInfo.getDeviceType());
                //  preparedStatement.setString(4, deviceInfo.getPlatform());
                //  preparedStatement.setString(5, deviceInfo.getPackageName());
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
        } catch (ClickHouseUnknownException | NullPointerException e) {
            Thread.sleep(200);
            assert preparedStatement != null;
            preparedStatement.executeBatch();
        } finally {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        }
    }

    /**
     * @param list        设备列表
     * @param isNewDevice 是否是新用户
     * @throws SQLException
     */
    public static void update(Connection connection, Set<String> list, boolean isNewDevice) throws SQLException, InterruptedException {
        StringBuilder updateSql = new StringBuilder();
        try {
            updateSql.append("ALTER TABLE dwh.etl_baichuan_daily ");
            /**
             * @parm tag 用户标注该设备是 0-未识别,1-新用户,2-老用户
             */
            if (isNewDevice) {
                updateSql.append("UPDATE tag = 1");
            } else {
                updateSql.append("UPDATE tag = 2");
            }
            StringBuilder inSql = new StringBuilder();
            for (String device : list) {
                inSql.append("'").append(device).append("',");
            }
            updateSql.append(" WHERE device_id IN (").append(inSql, 0, inSql.length() - 1).append(")");
            connection.createStatement().execute(String.valueOf(updateSql));
        } catch (ClickHouseUnknownException | NullPointerException e) {
            Thread.sleep(200);
            assert connection != null;
            connection.createStatement().execute(String.valueOf(updateSql));
        }
    }

}