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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
| @Service public class OnlineDataMigrationService { private final JdbcTemplate sourceJdbcTemplate; private final ShardingJdbcTemplate targetShardingTemplate; private final RedisTemplate<String, Object> redisTemplate;
@Component public class DualWriteStrategy { private volatile boolean enableDualWrite = false; private volatile boolean enableReadFromNew = false; @Transactional public void insertUser(User user) { sourceJdbcTemplate.update( "INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)", user.getUsername(), user.getEmail(), user.getPasswordHash() ); if (enableDualWrite) { try { String shardingKey = String.valueOf(user.getId()); targetShardingTemplate.update( "INSERT INTO users (id, username, email, password_hash) VALUES (?, ?, ?, ?)", new Object[]{user.getId(), user.getUsername(), user.getEmail(), user.getPasswordHash()}, shardingKey ); } catch (Exception e) { log.error("Dual write failed for user: " + user.getId(), e); } } } public User findUserById(Long userId) { String shardingKey = String.valueOf(userId); if (enableReadFromNew) { try { List<User> users = targetShardingTemplate.queryForList( "SELECT * FROM users WHERE id = ?", new Object[]{userId}, new UserRowMapper(), shardingKey ); if (!users.isEmpty()) { return users.get(0); } } catch (Exception e) { log.error("Read from new database failed, fallback to old", e); } } List<User> users = sourceJdbcTemplate.query( "SELECT * FROM users WHERE id = ?", new Object[]{userId}, new UserRowMapper() ); return users.isEmpty() ? null : users.get(0); } public void enableDualWrite() { this.enableDualWrite = true; log.info("Dual write enabled"); } public void enableReadFromNew() { this.enableReadFromNew = true; log.info("Read from new database enabled"); } public void disableDualWrite() { this.enableDualWrite = false; log.info("Dual write disabled"); } }
@Async public CompletableFuture<Void> migrateHistoricalData(String tableName, Long startId, Long endId) { log.info("Starting migration for table: {}, range: {} - {}", tableName, startId, endId); int batchSize = 1000; long currentId = startId; while (currentId <= endId) { long batchEndId = Math.min(currentId + batchSize - 1, endId); try { migrateBatch(tableName, currentId, batchEndId); String progressKey = "migration:progress:" + tableName; redisTemplate.opsForValue().set(progressKey, currentId); log.info("Migrated batch: {} - {} for table: {}", currentId, batchEndId, tableName); Thread.sleep(100); } catch (Exception e) { log.error("Migration failed for batch: {} - {}", currentId, batchEndId, e); String failedKey = "migration:failed:" + tableName; redisTemplate.opsForList().leftPush(failedKey, currentId + "-" + batchEndId); } currentId = batchEndId + 1; } log.info("Migration completed for table: {}", tableName); return CompletableFuture.completedFuture(null); } private void migrateBatch(String tableName, Long startId, Long endId) { String selectSql = String.format( "SELECT * FROM %s WHERE id >= ? AND id <= ? ORDER BY id", tableName ); List<Map<String, Object>> rows = sourceJdbcTemplate.queryForList( selectSql, startId, endId ); for (Map<String, Object> row : rows) { Long id = (Long) row.get("id"); String shardingKey = String.valueOf(id); StringBuilder insertSql = new StringBuilder("INSERT INTO "); insertSql.append(tableName).append(" ("); StringBuilder valuesSql = new StringBuilder(" VALUES ("); List<Object> values = new ArrayList<>(); boolean first = true; for (Map.Entry<String, Object> entry : row.entrySet()) { if (!first) { insertSql.append(", "); valuesSql.append(", "); } insertSql.append(entry.getKey()); valuesSql.append("?"); values.add(entry.getValue()); first = false; } insertSql.append(")").append(valuesSql).append(")"); targetShardingTemplate.update( insertSql.toString(), values.toArray(), shardingKey ); } }
public void verifyDataConsistency(String tableName, Long startId, Long endId) { log.info("Starting data consistency verification for table: {}", tableName); int batchSize = 1000; long currentId = startId; int inconsistentCount = 0; while (currentId <= endId) { long batchEndId = Math.min(currentId + batchSize - 1, endId); String selectSql = String.format( "SELECT id, username, email FROM %s WHERE id >= ? AND id <= ?", tableName ); List<Map<String, Object>> sourceRows = sourceJdbcTemplate.queryForList( selectSql, currentId, batchEndId ); for (Map<String, Object> sourceRow : sourceRows) { Long id = (Long) sourceRow.get("id"); String shardingKey = String.valueOf(id); try { List<Map<String, Object>> targetRows = targetShardingTemplate.queryForList( "SELECT id, username, email FROM users WHERE id = ?", new Object[]{id}, (rs, rowNum) -> { Map<String, Object> row = new HashMap<>(); row.put("id", rs.getLong("id")); row.put("username", rs.getString("username")); row.put("email", rs.getString("email")); return row; }, shardingKey ); if (targetRows.isEmpty()) { log.warn("Data missing in target for id: {}", id); inconsistentCount++; } else { Map<String, Object> targetRow = targetRows.get(0); if (!sourceRow.equals(targetRow)) { log.warn("Data inconsistent for id: {}, source: {}, target: {}", id, sourceRow, targetRow); inconsistentCount++; } } } catch (Exception e) { log.error("Verification failed for id: {}", id, e); inconsistentCount++; } } currentId = batchEndId + 1; } log.info("Data consistency verification completed. Inconsistent records: {}", inconsistentCount); } }
|