定时使命删除MongoDB汗青数据

[复制链接]
发表于 2025-12-19 00:44:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
媒介

MongoDB数据过多,导致存储资源飙升,为了低落资源,须要将汗青数据删除。
删除逻辑

添加设置文件控制删除逻辑
  1. syncconfig:
  2.   deleteMongoConfig:
  3.     #同步状态,true同步,false不同步
  4.     syncStatus: true
  5.     #删除数据的时间,一个月前
  6.     deleteDays: 31
  7.     #分布式锁key
  8.     lockRedisKey: order.sync.deleteMongo
  9.     #每次删除数量
  10.     limit: 2
复制代码
设置类
  1. @ConfigurationProperties(prefix = "syncconfig")
  2. @Configuration
  3. @RefreshScope
  4. @Data
  5. public class SyncConfig {
  6.     private DeleteMongoDto deleteMongoConfig;
  7.     @Data
  8.     @NoArgsConstructor
  9.     @AllArgsConstructor
  10.     public static class DeleteMongoDto {
  11.         /**
  12.          * 同步状态,true同步,false不同步
  13.          */
  14.         Boolean syncStatus = false;
  15.         /**
  16.          * 删除的天数(createTime)
  17.          */
  18.         Integer deleteDays = 186;
  19.         /**
  20.          * locakRedisKey,用于做分布式锁,防止定时任务执行时间较长,两个任务重叠执行
  21.          */
  22.         String lockRedisKey;
  23.         /**
  24.          * 每次数量
  25.          */
  26.         Integer limit = 1000;
  27.     }
  28. }
复制代码
焦点代码
  1.     @PostMapping("/deleteMongo")
  2.     public BaseResponse<String> deleteMongo() {
  3.         return orderService.deleteMongo();
  4.     }
复制代码
  1. @Override
  2.     public BaseResponse<String> deleteMongo() {
  3.         //获取配置信息
  4.         SyncConfig.DeleteMongoDto deleteMongoDto = syncConfig.getDeleteMongoConfig();
  5.         //判断同步是否开启
  6.         if (deleteMongoDto == null || !deleteMongoDto.getSyncStatus()) {
  7.             log.info("deleteMongosyncStatus=false,not sync");
  8.             return ResponseUtils.success("deleteMongosyncStatus=false,not sync");
  9.         }
  10.         Boolean lockStatus = false;
  11.         try {
  12.             lockStatus = redisLockService.acquireLock(deleteMongoDto.getLockRedisKey());
  13.             if (!lockStatus) {
  14.                 log.info("deleteMongo get lock fail,not sync");
  15.                 return ResponseUtils.fail("deleteMongo get lock fail,not sync");
  16.             }
  17.             //根据时间获取orderId
  18.             Long orderId = getOrderId(deleteMongoDto.getDeleteDays());
  19.             Query query = new Query(Criteria.where("orderId").lt(orderId));
  20.             query.limit(deleteMongoDto.getLimit());
  21.             // 使用投影来只选择orderId字段
  22.             query.fields().include("orderId");
  23.             // 这里不用分页是因为分页会查询total效率较低,数据量大的时候耗费资源
  24.             /*Pageable pageable = PageRequest.of(0, deleteMongoDto.getLimit());
  25.             Page<orderDao> page = orderDao.findByOrderIdLessThan(orderId, pageable);
  26.             List<Order> list = page.getContent();*/
  27.             List<Order> list=mongoTemplate.find(query,Order.class);
  28.             for (Orderitem :
  29.                     list) {
  30.                 orderDao.deleteById(item.getOrderId());
  31.             }
  32.             int count = 0;
  33.             if (CollectionUtils.isNotEmpty(list)) {
  34.                 count = list.size();
  35.             }
  36.             return ResponseUtils.success("deleteMongo success,count:" + count);
  37.         } catch (Exception ex) {
  38.             log.error("deleteMongo Exception:" + ex.getMessage());
  39.             return ResponseUtils.fail(ex.getMessage());
  40.         } finally {
  41.             //释放分布式锁
  42.             if (lockStatus) {
  43.                 redisLockService.releaseLock(deleteMongoDto.getLockRedisKey());
  44.             }
  45.         }
  46.     }
  47.     //生成半年前的orderId
  48.     private Long getOrderId(Integer deleteDays) {
  49.         LocalDateTime deleteTime = LocalDateTime.now().minusDays(deleteDays);
  50.         // 将LocalDateTime转换为毫秒值
  51.         ZonedDateTime utcZonedDateTime = deleteTime.atZone(ZoneId.systemDefault());
  52.         long milliseconds = utcZonedDateTime.toInstant().toEpochMilli();
  53.         Long orderId = (milliseconds / 1000) << 32;
  54.         return orderId;
  55.     }
复制代码
总结

这里是简朴的删除汗青数据逻辑,可以参考实行,分布式锁是为了防止重复调用,现实利用的时间也可以不消分布式锁。然后定时调用这个删除接口即可不停的删除汗青数据了
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表