当前位置:   article > 正文

springboot-mybatis/JPA流式查询_流式查询的话 用spring的streamingstatementhandler 还是mybatis

流式查询的话 用spring的streamingstatementhandler 还是mybatis的cursor ?

项目中有几个batch需要检查所有的用户参与的活动的状态,以前是使用分页,一页一页的查出来到内存再处理,但是随着数据量的增加,效率越来越低。于是经过一顿搜索,了解到流式查询这么个东西,不了解不知道,这一上手,爱的不要不要的,效率贼高。项目是springboot 项目,持久层用的mybatis,整好mybatis的版本后,又研究了一下JPA的版本,做事做全套,最后又整了原始的JDBCTemplate 版本。废话不多说,代码如下:

第一种方式: springboot + mybatis 流式查询(网上说的有三种,我觉得下面这种最简单,对业务代码侵入性最小)

a) service 层代码:

  1. package com.example.demo.service;
  2. import com.example.demo.bean.CustomerInfo;
  3. import com.example.demo.mapper.UserMapper;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.apache.ibatis.cursor.Cursor;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.jdbc.core.JdbcTemplate;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.transaction.annotation.Transactional;
  10. import javax.annotation.Resource;
  11. @Slf4j
  12. @Service
  13. public class TestStreamQueryService {
  14. @Resource
  15. private ApplicationContext applicationContext;
  16. @Resource
  17. private UserMapper userMapper;
  18. @Resource
  19. private JdbcTemplate jdbcTemplate;
  20. @Transactional
  21. public void testStreamQuery(Integer status) {
  22. mybatisStreamQuery(status);
  23. }
  24. private void mybatisStreamQuery(Integer status) {
  25. log.info("waiting for query.....");
  26. Cursor<CustomerInfo> customerInfos = userMapper.getCustomerInfo(status);
  27. log.info("finish query!");
  28. for (CustomerInfo customerInfo : customerInfos) {
  29. //处理业务逻辑
  30. log.info("===============>{}", customerInfo.getId());
  31. }
  32. }
  33. }

需要注意的有两点:

1.是userMapper 返回的是一个Cursor类型,其实就是用游标。然后遍历这个cursor,mybatis就会按照你在userMapper里设置的fetchSize 大小,每次去从数据库拉取数据

2.注意 testStreamQuery 方法上的 @transactional 注解,这个注解是用来开启一个事务,保持一个长连接(就是为了保持长连接采用的这个注解),因为是流式查询,每次从数据库拉取固定条数的数据,所以直到数据全部拉取完之前必须要保持连接状态。(顺便提一下,如果说不想让在这个testStreamQuery 方法内处理每条数据所作的更新或查询动作都在这个大事务内,那么可以另起一个方法 使用required_new 的事务传播,使用单独的事务去处理,使事务粒度最小化。如下图:)

b) mapper 层代码:

  1. package com.example.demo.mapper;
  2. import com.example.demo.bean.CustomerInfo;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.apache.ibatis.cursor.Cursor;
  5. import org.springframework.stereotype.Repository;
  6. @Mapper
  7. @Repository
  8. public interface UserMapper {
  9. Cursor<CustomerInfo> getCustomerInfo(Integer status);
  10. }

mapper.xml 

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.demo.mapper.UserMapper">
  4. <select id="getCustomerInfo" resultType="com.example.demo.bean.CustomerInfo" fetchSize="2" resultSetType="FORWARD_ONLY">
  5. select * from table_name where status = #{status} order by id
  6. </select>
  7. </mapper>

 UserMapper.java 无需多说,其实要注意的是mapper.xml中的配置:fetchSize 属性就是上一步说的,每次从数据库取多少条数据回内存。resultSetType属性需要设置为 FORWARD_ONLY, 意味着,查询只会单向向前读取数据,当然这个属性还有其他两个值,这里就不展开了。

至此,springboot+mybatis 流式查询就可以用起来了,以下是执行结果截图:

c)读取200万条数据,每次fetchSize读取1000条,batch总用时50s左右执行完,速度是相当可以了,堆内存占用不超过250M,这里用的数据库是本地docker起的一个postgre, 远程数据库的话,耗时可能就不太一样了

 


第二种方式:springboot+JPA 流式查询

a)  service层代码:

  1. package com.example.demo.service;
  2. import com.example.demo.dao.CustomerInfoDao;
  3. import com.example.demo.mapper.UserMapper;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Transactional;
  9. import javax.annotation.Resource;
  10. import javax.persistence.EntityManager;
  11. import java.util.stream.Stream;
  12. @Slf4j
  13. @Service
  14. public class TestStreamQueryService {
  15. @Resource
  16. private ApplicationContext applicationContext;
  17. @Resource
  18. private UserMapper userMapper;
  19. @Resource
  20. private JdbcTemplate jdbcTemplate;
  21. @Resource
  22. private CustomerInfoDao customerInfoDao;
  23. @Resource
  24. private EntityManager entityManager;
  25. @Transactional(readOnly = true)
  26. public void testStreamQuery(Integer status) {
  27. jpaStreamQuery(status);
  28. }
  29. public void jpaStreamQuery(Integer status) {
  30. Stream<com.example.demo.entity.CustomerInfo> stream = customerInfoDao.findByStatus(status);
  31. stream.forEach(customerInfo -> {
  32. entityManager.detach(customerInfo); //解除强引用,避免数据量过大时,强引用一直得不到GC 慢慢会OOM
  33. log.info("====>id:[{}]", customerInfo.getId());
  34. });
  35. }
  36. }

 注意点:1. 这里的@transactional(readonly=true) 这里的作用也是保持一个长连接的作用,同时标注这个事务是只读的。

                2. 循环处理数据时需要先:entityManager.detach(customerInfo); 解除强引用,避免数据量过大时,强引用一直得不到GC 慢慢会OOM。

b) dao层代码:

  1. package com.example.demo.dao;
  2. import com.example.demo.entity.CustomerInfo;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.QueryHints;
  5. import org.springframework.stereotype.Repository;
  6. import javax.persistence.QueryHint;
  7. import java.util.stream.Stream;
  8. import static org.hibernate.jpa.QueryHints.HINT_FETCH_SIZE;
  9. @Repository
  10. public interface CustomerInfoDao extends JpaRepository<CustomerInfo, Long> {
  11. @QueryHints(value=@QueryHint(name = HINT_FETCH_SIZE,value = "1000"))
  12. Stream<CustomerInfo> findByStatus(Integer status);
  13. }

 注意点:1.dao方法的返回值是 Stream 类型

                2.dao方法的注解:@QueryHints(value=@QueryHint(name = HINT_FETCH_SIZE,value = "1000"))  这个注解是设置每次从数据库拉取多少条数据,自己可以视情况而定,不可太大,反而得不偿失,一次读取太多数据数据库也是很耗时间的。。。

自此springboot + jpa 流式查询代码就贴完了,可以happy了,下面是执行结果:

c)  batch读取两百万条数据,堆内存使用截图:

 

每次fetchSize拉取1000条数据,可以看到内存使用情况:初始内存不到100M,batch执行过程中最高内存占用300M出头然后被GC。读取效率:不到一分钟执行完(处理每一条数据只是打印一下id),速度还是非常快的。

d)  读取每一条数据时,不使用 entityManager.detach(customerInfo),内存使用截图:

最终OOM了,这里的entityManager.detach(customerInfo) 很关键。


第三种方式:使用JDBC template 流式查询

其实这种方式就是最原始的jdbc的方式,代码侵入性很大,逼不得已也不会使用

a) 上代码:

  1. package com.example.demo.service;
  2. import com.example.demo.dao.CustomerInfoDao;
  3. import com.example.demo.mapper.UserMapper;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.stereotype.Service;
  8. import javax.annotation.Resource;
  9. import javax.persistence.EntityManager;
  10. import java.sql.Connection;
  11. import java.sql.PreparedStatement;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. @Slf4j
  15. @Service
  16. public class TestStreamQueryService {
  17. @Resource
  18. private ApplicationContext applicationContext;
  19. @Resource
  20. private UserMapper userMapper;
  21. @Resource
  22. private JdbcTemplate jdbcTemplate;
  23. @Resource
  24. private CustomerInfoDao customerInfoDao;
  25. @Resource
  26. private EntityManager entityManager;
  27. public void testStreamQuery(Integer status) {
  28. jdbcStreamQuery(status);
  29. }
  30. private void jdbcStreamQuery(Integer status) {
  31. Connection conn = null;
  32. PreparedStatement pstmt = null;
  33. ResultSet rs = null;
  34. try {
  35. conn = jdbcTemplate.getDataSource().getConnection();
  36. conn.setAutoCommit(false);
  37. pstmt = conn.prepareStatement("select * from customer_info where status = " + status + " order by id", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  38. pstmt.setFetchSize(1000);
  39. pstmt.setFetchDirection(ResultSet.FETCH_FORWARD);
  40. rs = pstmt.executeQuery();
  41. while (rs.next()) {
  42. long id = rs.getLong("id");
  43. String name = rs.getString("name");
  44. String email = rs.getString("email");
  45. int sta = rs.getInt("status");
  46. log.info("=========>id:[{}]", id);
  47. }
  48. } catch (SQLException throwables) {
  49. throwables.printStackTrace();
  50. } finally {
  51. try {
  52. rs.close();
  53. pstmt.close();
  54. conn.close();
  55. } catch (SQLException throwables) {
  56. throwables.printStackTrace();
  57. }
  58. }
  59. }
  60. }

b) 执行结果:200万数据不到50秒执行完,内存占用最高300M

 

自此,针对不同的持久层框架, 使用不同的流式查询,其实本质是一样的,归根结底还是驱动jdbc做事情。以上纯个人见解,若有不当之处,请不吝指出,共同进步!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号