毫秒级删除MySQL数据库百万条数据

最近遇到了清理历史数据的需求,需要去清楚数据库中的数据,但是DBA对数据库的删除任务做了各种限制,比如一个事务的连接不能超过60s,不加事务的操作不能超过120s。也就是说大概百万级的数据需要在60s内全部删除。

原本是想先将符合条件所有记录全部查出来,再去做分批删除,没想到查询语句就超时了

// 查询在update日期之前的所有记录
List<Result> results = resultRepository.findByUpdateBefore(updDate);
// 按照500条分组
List<List<Result>> partition = Lists.partition(results, 500);
// 分组删除
for (List<Result> resultList : partition){
     resultRepository.deleteInBatch(resultList);
}

虽然在upDate上有索引,但是数据量还是太大了,在60s之内没有查出数据。

只能分页查询,再循环删除了,这次在500ms之内就删除了,但是这个while循环总感觉写的不好,不知道有没有其他的办法。

while (true){
   try{
       Pageable pageable = PageRequest.of(0,500);
       List<Result> results = resultRepository.findByUpdDateBefore(updDate,pageable);
       if (CollectionUtils.isNotEmpty(results)){
          resultRepository.deleteInBatch(results);
       }else{
          return;
       }
   }catch (Exception e){
       log.info("删除result失败:{}",e.getMessage());
       throw e;
   }
}

猜你喜欢

转载自blog.csdn.net/yshuoo/article/details/84524261