使用mongoTemplate id增量快速遍历整张表的所有数据

我使用了junit,自己验证性的写了一下,感觉速度还是非常快的,这个。现在由于时间和场地的原因,我只提供方法的代码。对于全套的测试环境,等我这段时间忙完,我把前代码整理一下,放在我的github上,到时候欢迎小伙伴follow and star。

老规矩,直接上代码。

DAO层, Lexicon根据自己mongodb的表结构来定义

    @Resource
    MongoTemplate mongoTemplate;

    public List<Lexicon> findLexiconById(String _id) {
        Query query = new Query();
        if(StringUtils.isNotBlank(_id)) {
            query.addCriteria(Criteria.where("_id").gt(new ObjectId(_id)));
        }
        query.with(new Sort(Sort.Direction.ASC, "_id")).limit(200);
        return mongoTemplate.find(query, Lexicon.class);
    }


这里的LexiconDao就是上面的DAO层

    @Autowired
    LexiconDao lexiconDao;

    String _id = null;
    int total = 0;

    //定义一个队列
    Queue<Lexicon> queue = new LinkedList<>();


    @Test
    public void testfindLexiconById() {
        Lexicon entity = null;
        int i = 1;
        //从读取数据中取出对象
        while((entity = getLexicon()) != null) {

        }

    }

    //读取数据
    public void readData() {
        List<Lexicon> list = lexiconDao.findLexiconById(_id);
        if(!CollectionUtils.isEmpty(list)) {
            queue.addAll(list);
            _id = list.get(list.size() - 1).getId();
            total = total + list.size();
        } else {
            _id = null;
        }
    }

    //从队列中获得个个对象
    public Lexicon getLexicon() {
        Lexicon entity = queue.poll();
        if(entity == null) {
            readData();
            entity = queue.poll();
        }
        return entity;
    }


代码在生产环境下验证过,自己的水平原因可能存在错误和想给意见的,email: [email protected]

猜你喜欢

转载自blog.csdn.net/hello_ray/article/details/80817433