赞
踩
场景:
从db中查询数据,并根据查询的结果去构造参数,然后去更新另一张表。由于一次性查询出的结果量过大,很有可能造成OOM。
解决办法:
采用mybais流式查询
废话不多说,先上完成后的代码:
- @Service
- @Slf4j
- public class MarcInstanceServiceImpl implements MarcInstanceService {
-
- @Autowired
- private MarcInstanceDao marcInstanceDao;
- @Autowired
- private InstanceInfoDao instanceInfoDao;
-
- /**
- * 重新生成other_title
- */
- @Override
- @Transactional(rollbackFor = Exception.class)
- public Integer rebuildOtherTitle() throws IOException {
- AtomicInteger count = new AtomicInteger(0);
- try (Cursor<MarcInstanceEntity> cursor = marcInstanceDao.getRepeat517Marc()) {
- cursor.forEach(marcInstanceEntity -> {
- // 构造参数
- // 省略。。。
- // 去做更新表操作
- count.addAndGet(instanceInfoDao.updateOtherTitleById(marcInstanceEntity));
- log.info("更新第{}条other_title", count.get());
- });
- }
- log.info("总共更新{}条other_title", count.get());
- return count.get();
- }
- }
其中:
1)marcInstanceDao.getRepeat517Marc()会做大数据量的查询,大概几十万左右。
2)count.addAndGet是计数使用。
3)instanceInfoDao.updateOtherTitleById是根据查询到的结果去更新表。
经过少量数据测试,没有问题。
// todo 进行大批量的数据测试,有结果后会更新到这儿。。。
2022-05-18更新:
经过测试,不到11万的数据量,用时大概3分钟左右,正常结束。
2022-05-20更新:
生产环境OOM了。。。我真是个傻狗。
事情经过:接口如上所写,然后启动给了1024M内存,调用接口,结果OOM。然后重新给2048M,调用接口,还是OOM。最后不限制内存了才能正常调用。
所有这个流式查询并没有解决OOM的问题,原因大概猜到了,应该是:marcInstanceDao.getRepeat517Marc()过大导致的。
综上:这种流式查询并不能解决可能出现OOM的问题。后续待优化。。。
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。