| | |
| | | public class CleanVehicleGpsTask { |
| | | private static final Logger log = LoggerFactory.getLogger(CleanVehicleGpsTask.class); |
| | | |
| | | /** 每批删除数量 */ |
| | | private static final int BATCH_SIZE = 10000; |
| | | /** 每批间隔时间(毫秒),避免连续删除对数据库压力过大 */ |
| | | private static final long BATCH_INTERVAL_MS = 500; |
| | | |
| | | @Autowired |
| | | private IVehicleGpsService vehicleGpsService; |
| | | |
| | | /** |
| | | * 清理车辆GPS历史数据 |
| | | * 清理车辆GPS历史数据(保留最近2个月,分批删除) |
| | | */ |
| | | public void cleanVehicleGpsData() { |
| | | try { |
| | | // log.info("开始清理车辆GPS历史数据"); |
| | | int count = vehicleGpsService.deleteVehicleGpsBeforeDate(); |
| | | // log.info("清理车辆GPS历史数据完成,共清理{}条记录", count); |
| | | log.info("开始清理车辆GPS历史数据(保留最近2个月,每批 {} 条)", BATCH_SIZE); |
| | | int totalCount = 0; |
| | | int batchCount; |
| | | int round = 0; |
| | | do { |
| | | batchCount = vehicleGpsService.deleteVehicleGpsBeforeDateBatch(BATCH_SIZE); |
| | | totalCount += batchCount; |
| | | round++; |
| | | log.info("第 {} 批清理完成,本批删除 {} 条,已删除合计 {} 条", round, batchCount, totalCount); |
| | | if (batchCount == BATCH_SIZE) { |
| | | // 还有数据,稍作休眠再继续 |
| | | Thread.sleep(BATCH_INTERVAL_MS); |
| | | } |
| | | } while (batchCount == BATCH_SIZE); |
| | | |
| | | log.info("清理车辆GPS历史数据完成,共 {} 批,删除 {} 条记录", round, totalCount); |
| | | |
| | | if (totalCount > 0) { |
| | | log.info("开始执行 OPTIMIZE TABLE,回收磁盘空间(此操作耗时较长,请勿中断)"); |
| | | vehicleGpsService.optimizeVehicleGpsTable(); |
| | | log.info("OPTIMIZE TABLE 执行完成"); |
| | | } else { |
| | | log.info("本次无可清理的记录,跳过 OPTIMIZE TABLE"); |
| | | } |
| | | } catch (Exception e) { |
| | | log.error("清理车辆GPS历史数据异常", e); |
| | | } |