定时清理 MongoDB 历史数据

MongoDB Spring Boot cron About 1,567 words

需求

每晚9点至第二天凌晨5点,清理6个月前的历史数据。

思路

执行定时任务,生成6个月前的ObjectId,判断小于该ObjectId的,批量删除(每次10000条删除)。因为默认_id有索引,而无需再根据自定义的create_ts等时间字段创建索引再删除了,可直接利用ObjectId来完成,因为ObjectId本来就由机器码+线程id+时间戳生成,故可以推得时间戳和使用指定时间生成ObjectId

代码

实现方案使用Spring Boot + Spring Data MongoDB完成。

0 * 21-23,0-5 * * ?定时任务跨天执行。

new ObjectId(Date)指定时间生成ObjectId

@Slf4j
@SpringBootApplication
public class DemoApplication {

    @Resource
    private MongoTemplate mongoTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Scheduled(cron = "0 * 21-23,0-5 * * ?")
    public void cron() {
        clean();
    }

    public void clean() {
        LocalDate localDate = LocalDate.now().minusMonths(6);
        System.out.println(localDate.toString());
        Date from = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
        ObjectId objectId = new ObjectId(from);
        System.out.println(localDate.toString() + "#" + objectId.toHexString());
        log.info("now#{}, ObjectId#{}", localDate.toString(), objectId.toHexString());

        Query query = Query.query(Criteria.where("_id").lt(objectId)).limit(10000);

        long now = System.currentTimeMillis();

        DeleteResult deleteResult = mongoTemplate.remove(query, Document.class, "test_col");

        log.info("delete test_col result#{}-{}, cost#{}", deleteResult.wasAcknowledged(), deleteResult.getDeletedCount(), System.currentTimeMillis() - now);

    }

}

完整代码

https://github.com/fendoudebb/learning/tree/master/java/learn-spring-boot/mongo-clean

Views: 5,212 · Posted: 2020-06-02

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh