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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
|
@Service public class GrayMigrationStrategyService {
@Autowired private SourceDatabaseService sourceDatabaseService;
@Autowired private TargetDatabaseService targetDatabaseService;
@Autowired private MigrationConfigService migrationConfigService;
@Autowired private DataSyncService dataSyncService;
public void grayMigration(String tableName, GrayMigrationConfig config) { try { initializeGrayMigration(tableName, config);
executeGrayMigration(tableName, config);
monitorMigrationProgress(tableName, config);
validateMigrationResult(tableName, config);
completeGrayMigration(tableName, config);
} catch (Exception e) { log.error("灰度迁移失败", e); throw new MigrationException("灰度迁移失败", e); } }
private void initializeGrayMigration(String tableName, GrayMigrationConfig config) { try { migrationConfigService.updateMigrationStatus(tableName, MigrationStatus.IN_PROGRESS);
MigrationTask task = createMigrationTask(tableName, config); migrationConfigService.saveMigrationTask(task);
dataSyncService.initializeDataSync(tableName, config);
log.info("灰度迁移初始化完成: {}", tableName);
} catch (Exception e) { log.error("初始化灰度迁移失败", e); throw new MigrationException("初始化灰度迁移失败", e); } }
private MigrationTask createMigrationTask(String tableName, GrayMigrationConfig config) { MigrationTask task = new MigrationTask(); task.setTableName(tableName); task.setMigrationType(MigrationType.GRAY); task.setGrayRatio(config.getGrayRatio()); task.setBatchSize(config.getBatchSize()); task.setStatus(TaskStatus.PENDING); task.setCreateTime(new Date());
return task; }
private void executeGrayMigration(String tableName, GrayMigrationConfig config) { try { MigrationTask task = migrationConfigService.getMigrationTask(tableName);
int batchSize = config.getBatchSize(); int offset = 0;
while (true) { List<Map<String, Object>> batchData = sourceDatabaseService.queryBatch(tableName, offset, batchSize);
if (batchData.isEmpty()) { break; }
List<Map<String, Object>> grayData = selectGrayData(batchData, config.getGrayRatio());
migrateBatchData(tableName, grayData);
updateMigrationProgress(task, batchData.size());
offset += batchSize;
Thread.sleep(config.getSleepInterval()); }
task.setStatus(TaskStatus.COMPLETED); migrationConfigService.updateMigrationTask(task);
} catch (Exception e) { log.error("执行灰度迁移失败", e); throw new MigrationException("执行灰度迁移失败", e); } }
private List<Map<String, Object>> selectGrayData(List<Map<String, Object>> batchData, double grayRatio) { List<Map<String, Object>> grayData = new ArrayList<>();
for (Map<String, Object> data : batchData) { String primaryKey = data.get("id").toString(); int hash = Math.abs(primaryKey.hashCode()); double ratio = (double) (hash % 100) / 100.0;
if (ratio < grayRatio) { grayData.add(data); } }
return grayData; }
private void migrateBatchData(String tableName, List<Map<String, Object>> batchData) { try { for (Map<String, Object> data : batchData) { targetDatabaseService.insert(tableName, data);
recordMigrationLog(tableName, data); } } catch (Exception e) { log.error("迁移批量数据失败", e); throw new MigrationException("迁移批量数据失败", e); } }
private void recordMigrationLog(String tableName, Map<String, Object> data) { try { MigrationLog log = new MigrationLog(); log.setTableName(tableName); log.setPrimaryKeyValue(data.get("id")); log.setOperation("INSERT"); log.setStatus("SUCCESS"); log.setCreateTime(new Date());
migrationConfigService.saveMigrationLog(log);
} catch (Exception e) { log.error("记录迁移日志失败", e); } }
private void updateMigrationProgress(MigrationTask task, int processedCount) { try { task.setProcessedCount(task.getProcessedCount() + processedCount); task.setProgress((double) task.getProcessedCount() / task.getTotalCount() * 100);
migrationConfigService.updateMigrationTask(task);
} catch (Exception e) { log.error("更新迁移进度失败", e); } }
private void monitorMigrationProgress(String tableName, GrayMigrationConfig config) { try { Thread monitorThread = new Thread(() -> { while (true) { try { MigrationTask task = migrationConfigService.getMigrationTask(tableName);
if (task.getStatus() == TaskStatus.COMPLETED) { break; }
checkMigrationProgress(task);
Thread.sleep(config.getMonitorInterval());
} catch (Exception e) { log.error("监控迁移进度失败", e); break; } } });
monitorThread.start();
} catch (Exception e) { log.error("启动迁移进度监控失败", e); } }
private void checkMigrationProgress(MigrationTask task) { try { List<MigrationLog> errorLogs = migrationConfigService.getErrorMigrationLogs(task.getTableName());
if (!errorLogs.isEmpty()) { log.warn("发现迁移异常: {}", errorLogs.size()); handleMigrationErrors(task, errorLogs); }
double migrationSpeed = calculateMigrationSpeed(task); if (migrationSpeed < task.getMinSpeed()) { log.warn("迁移速度过慢: {}", migrationSpeed); adjustMigrationStrategy(task); }
} catch (Exception e) { log.error("检查迁移进度失败", e); } }
private void handleMigrationErrors(MigrationTask task, List<MigrationLog> errorLogs) { try { for (MigrationLog errorLog : errorLogs) { retryMigration(task.getTableName(), errorLog); } } catch (Exception e) { log.error("处理迁移异常失败", e); } }
private void retryMigration(String tableName, MigrationLog errorLog) { try { Map<String, Object> data = sourceDatabaseService.queryByPrimaryKey(tableName, errorLog.getPrimaryKeyValue());
if (data != null) { targetDatabaseService.insert(tableName, data);
errorLog.setStatus("SUCCESS"); errorLog.setRetryCount(errorLog.getRetryCount() + 1); migrationConfigService.updateMigrationLog(errorLog); }
} catch (Exception e) { log.error("重试迁移失败", e); } }
private double calculateMigrationSpeed(MigrationTask task) { try { long currentTime = System.currentTimeMillis(); long startTime = task.getCreateTime().getTime(); long duration = currentTime - startTime;
if (duration == 0) { return 0; }
return (double) task.getProcessedCount() / duration * 1000;
} catch (Exception e) { log.error("计算迁移速度失败", e); return 0; } }
private void adjustMigrationStrategy(MigrationTask task) { try { int newBatchSize = task.getBatchSize() * 2; task.setBatchSize(newBatchSize);
migrationConfigService.updateMigrationTask(task);
log.info("调整迁移策略: 批次大小调整为 {}", newBatchSize);
} catch (Exception e) { log.error("调整迁移策略失败", e); } }
private void validateMigrationResult(String tableName, GrayMigrationConfig config) { try { DataConsistencyResult result = dataSyncService.validateDataConsistency(tableName);
if (!result.isConsistent()) { log.error("数据一致性校验失败: {}", result.getErrorMessage()); throw new MigrationException("数据一致性校验失败: " + result.getErrorMessage()); }
PerformanceTestResult performanceResult = dataSyncService.performanceTest(tableName);
if (performanceResult.getResponseTime() > config.getMaxResponseTime()) { log.warn("性能测试不达标: 响应时间 {}", performanceResult.getResponseTime()); }
log.info("迁移结果验证通过: {}", tableName);
} catch (Exception e) { log.error("验证迁移结果失败", e); throw new MigrationException("验证迁移结果失败", e); } }
private void completeGrayMigration(String tableName, GrayMigrationConfig config) { try { migrationConfigService.updateMigrationStatus(tableName, MigrationStatus.COMPLETED);
cleanupTemporaryData(tableName);
sendCompletionNotification(tableName, config);
log.info("灰度迁移完成: {}", tableName);
} catch (Exception e) { log.error("完成灰度迁移失败", e); throw new MigrationException("完成灰度迁移失败", e); } }
private void cleanupTemporaryData(String tableName) { try { migrationConfigService.cleanupMigrationLogs(tableName);
migrationConfigService.cleanupTemporaryTables(tableName);
} catch (Exception e) { log.error("清理临时数据失败", e); } }
private void sendCompletionNotification(String tableName, GrayMigrationConfig config) { try { EmailNotification email = new EmailNotification(); email.setSubject("数据迁移完成通知"); email.setContent("表 " + tableName + " 的灰度迁移已完成"); email.setRecipients(config.getNotificationRecipients());
notificationService.sendEmail(email);
} catch (Exception e) { log.error("发送完成通知失败", e); } } }
|