PageHelper缓存在线程中的分页对象未释放问题排查方案

项目背景

  • 本项目旨在为金融行业客户提供一套完整的解决方案,共分为三个模块。其中,接口模块负责与数据库和外部请求进行对接,以实现数据的传输和处理。然而,在接口模块的功能测试过程中出现了一些问题,需要对其进行优化

问题现象

  • 在测试过程中,我们偶尔发现接口请求异常。经过查看日志,我们发现主要问题出现在查询语句后面被意外拼接了分页语句limit 100

问题排查过程

  • 经过阅读分析PageHelper官方文档之后,发现官方提示如果PageHelper.startPage对象后未使用该对象,就会分页对象会一直留在ThreadLocal中,直到下次对应线程使用到缓存才会清理掉。官方的示例如下:
PageHelper.startPage(1, 10);
List<Country> list;
if(param1 != null){
    list = countryMapper.selectIf(param1);
} else {
    list = new ArrayList<Country>();
}
  • 排查项目中使用到的PageHelper场景,均未发现代码中有使用PageHelper未释放的问题。故而知道非上述场景代码影响。
  • 经过阅读PageHelper源码发现PageHelper是通过拦截器的方式注入到mybatis拦截器中,而且PageHelper.startPage方法并不校验拦截器是否注入完成,故而猜测是调用时PageHelper拦截器未注入到mybatis拦截器导致的。
    • 问题复现:将PageHelper对应的查询语句放到@PostConstruct标注的方法中,配置mybati打印查询日志。启动服务后发现执行sql并未拼接查询语句,故而了解到的确存在这样的场景可能有问题。
  • 经过分析,我们在接口模块除了H5请求会转发进来,还有一个定时任务服务会直接发送RPC请求进来,RPC请求并不依赖服务注册,所以猜测是定时任务在服务尚未完全启动时调用服务导致。
    • 问题复现:将定时任务调用频率调整为1秒钟调用一次。重启服务之后,服务刚启动的几次调用都未拼接分页语句,等服务启动完成后,再调用就会拼接分页语句了。
  • 从上述场景中可以了解到,我们碰到的问题,正是因为PageHelper未启动成功就调用框架导致的。

问题分析

  • mybatis使用spring.factories配置文件配置的方式注入@Configuration
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

  • bean初始化是通过AbstractApplicationContext.refresh方法初始化,而mybatis和PageHelper均是使用finishBeanFactoryInitialization

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// 初始化懒加载bean
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}
	

MybatisAutoConfiguration.sqlSessionFactory

@Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
      factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    factory.setConfiguration(properties.getConfiguration());
    if (this.properties.getConfigurationProperties() != null) {
      factory.setConfigurationProperties(this.properties.getConfigurationProperties());
    }
    // 初始化mybatis拦截器
    if (!ObjectUtils.isEmpty(this.interceptors)) {
      factory.setPlugins(this.interceptors);
    }
    if (this.databaseIdProvider != null) {
      factory.setDatabaseIdProvider(this.databaseIdProvider);
    }
    if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
      factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
    }
    if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
      factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
    }
    if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
      factory.setMapperLocations(this.properties.resolveMapperLocations());
    }

    return factory.getObject();
  }

PageHelperAutoConfiguration.afterPropertiesSet继承InitializingBean,初始化bean时会自动调用afterPropertiesSet方法

  @Override
    public void afterPropertiesSet() throws Exception {
        PageInterceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        //先把一般方式配置的属性放进去
        properties.putAll(pageHelperProperties());
        //在把特殊配置放进去,由于close-conn 利用上面方式时,属性名就是 close-conn 而不是 closeConn,所以需要额外的一步
        properties.putAll(this.properties.getProperties());
        interceptor.setProperties(properties);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            if (!containsInterceptor(configuration, interceptor)) {
                configuration.addInterceptor(interceptor);
            }
        }
    }

问题总结

  • 通过排查问题,可以总结得到PageHelper在使用时需要注意以下几个方面问题:
      1. 使用PageHelper.startPage方法时需要紧跟查询语句。主要是因为PageHelper.startPage会将分页语句缓存当前线程的ThreadLocal中,并只有在执行完sql之后才会在拦截器中清理
      1. PageHelper分页方法不用用在@PostConstruct标注的业务方法中。主要是因为PageHelper初始化较晚,很可能业务方法已经执行了但是PageHelper的拦截器还未注入到mybatis拦截器中
      1. 使用PageHelper时需要考虑业务方法是否可能在服务尚未启动完成时调用。原因同上
  • 团队后续已达成共识,非必要不再使用PageHelper分页,如果确认要用PageHelper分页需要手动清理缓存在线程中的分页数据。官方推荐代码如下:
List<Country> list;
if(param1 != null){
    PageHelper.startPage(1, 10);
    try{
        list = countryMapper.selectAll();
    } finally {
        PageHelper.clearPage();
    }
} else {
    list = new ArrayList<Country>();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吴代庄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值