SpringBoot使用 druid 连接池来优化分页语句

 更新时间:2020年11月06日 09:48:24   作者:如梦技术  
这篇文章主要介绍了SpringBoot使用 druid 连接池来优化分页语句,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、前言

一个老系统随着数据量越来越大,我们察觉到部分分页语句拖慢了我们的速度。

鉴于老系统的使用方式,不打算使用pagehelper和mybatis-plus来处理,加上系统里使用得是druid连接池,考虑直接使用druid来优化。

二、老代码

老代码是使用得一个mybatis插件进行的分页,分页的核心代码如下:

// 记录统计的 sql
String countSql = "select count(0) from (" + sql+ ") tmp_count";
PreparedStatement countStmt = connection.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
setParameters(countStmt, mappedStatement, countBS,parameterObject);

在原始的 sql 外面包装了一个 count sql,当然很多插件都是这样做的。

三、druid 的 PagerUtil

示例 sql(有比较复杂的坐标计算)

SELECT g.*
  , ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN((? * PI() / 180 - t.latitude * PI() / 180) / 2), 2) + COS(? * PI() / 180) * COS(t.latitude * PI() / 180) * POW(SIN((? * PI() / 180 - t.longitude * PI() / 180) / 2), 2))), 2) AS distancecd
  , t.agentname, t.agentlogo, t.compaddress
FROM t_bas_integral_goods g
  LEFT JOIN t_bas_agent t ON g.agentid = t.AGENTID
WHERE t.AGENTTYPE = '2'
  AND t.pass = '0'
  AND t.dl_type = '4'
  AND g.type = 0
ORDER BY distancecd ASC

使用 Druid 生成 count sql:

String countSql = PagerUtils.count(sql, DbType.mysql);
System.out.println(countSql);

输出:

SELECT COUNT(*)
FROM t_bas_integral_goods g
 LEFT JOIN t_bas_agent t ON g.agentid = t.AGENTID
WHERE t.AGENTTYPE = '2'
 AND t.pass = '0'
 AND t.dl_type = '4'
 AND g.type = 0

我们可以看到优化后的 count sql 变得十分简洁,坐标计算的都已经丢弃掉。 注意:PagerUtil还有limit方法用来生成limit语句,感兴趣的同学可以自行试验。

四、改造mybatis分页插件

4.1 踩坑之路

看到上面 druid PagerUtils count 的优化效果,立马开始改造起来,起初只改掉了countSql,

String countSql = PagerUtils.count(sql, dbType);
PreparedStatement countStmt = connection.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
setParameters(countStmt, mappedStatement, countBS,parameterObject);

启动起来测试一番就发现报错了,因为原始 sql 中含有?变量,优化后的 sql 已经没有变量了,插件还会继续给他设置变量。 我们要怎么解决这个问题呢?

我们再回头看看pagehelper和mybatis-plus是怎么实现的!它俩都是基于jsqlparser对 sql 进行解析,然后处理。

要多加一个jsqlparser?没必要没必要,druid 的 sql 解析功能也是很强大的,我看了看PagerUtils.count方法的源码,大不了用 druid 的 sql 解析实现一遍。

看了看源码之后我陷入了沉思,有必要搞这么复杂么?有没有更好的方法?我反复 debug 发现了,DynamicSqlSource中有带#{xxx}这样的原始 sql,

那么我是否可以使用 druid 先对这种 mybatis 占位符的 sql 进行优化呢?我们来试试:

示例 sql:

select * from xxx where type = #{type} order by xx

输出:

SELECT COUNT(*)
FROM xxx
WHERE type = #{type}

完美!!! 4.2 继续踩坑

然而直接在 Mapper 上注解的 sql 还是有问题,拿不到原始的 sql,debug 发现 RawSqlSource 在构造器里就将 sql 处理成了?号挂参的形式。

@Select("select * from xxx where type = #{type} order by xx")
Object test(@Param("type") String type);

那么我只能看看能不能扩展它,我找到了它是在XMLLanguageDriver里进行初始化,这下好办了,因为我之前扩展过XMLLanguageDriver,它是可以自定义配置的。 于是我重写了RawSqlSource, 添加上了包含 mybatis 参数占位符(#{})的rawSql字段。

/**
 * 原始 sql,用于方便 druid 工具进行分页
 *
 * @author L.cm
 */
public class MicaRawSqlSource implements SqlSource {
  private final String rawSql;
  private final SqlSource sqlSource;
  public MicaRawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
    this(configuration, getSql(configuration, rootSqlNode), parameterType);
  }
  public MicaRawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    Class<?> clazz = parameterType == null ? Object.class : parameterType;
    this.rawSql = sql;
    this.sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
  }
  // ... ...
}

自此全部逻辑已经走通,我们再来看看我们的PagePlugin核心代码:

// 进行分页
Configuration configuration = mappedStatement.getConfiguration();
SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
Class<?> parameterType = parameterObject.getClass();
Connection connection = (Connection) invocation.getArgs()[0];
// 1. 对 sql 进行判断,如果没有 ? 号,则直接处理
String boundRawSql = boundSql.getSql();
if (boundRawSql.indexOf(CharPool.QUESTION_MARK) == -1) {
  // 不包含 ? 号
  String countSql = PagerUtils.count(boundRawSql, dbType);
  SqlSource newSqlSource = sqlSourceParser.parse(countSql, parameterType, new HashMap<>());
  BoundSql newBoundSql = newSqlSource.getBoundSql(parameterObject);
  int count = getCount(connection, mappedStatement, parameterObject, newBoundSql);
  StringBuilder sqlBuilder = new StringBuilder(boundRawSql);
  Page page = getPageParam(parameterObject, sqlBuilder, count);
  String pageSql = generatePageSql(sqlBuilder.toString(), dbType, page);
  // 将分页sql语句反射回BoundSql.
  setField(boundSql, "sql", pageSql);
  return invocation.proceed();
}
// 2. 按 SqlSource 进行解析
SqlSource sqlSource = mappedStatement.getSqlSource();
// xml 中的动态 sql
int count;
if (sqlSource instanceof DynamicSqlSource) {
  SqlNode rootSqlNode = PagePlugin.getField(sqlSource, "rootSqlNode");
  DynamicContext context = new DynamicContext(configuration, parameterObject);
  rootSqlNode.apply(context);
  // 生成 count sql,带 #{xxx} 变量的 sql
  String countSql = PagerUtils.count(context.getSql(), dbType);
  SqlSource newSqlSource = sqlSourceParser.parse(countSql, parameterType, context.getBindings());
  BoundSql newBoundSql = newSqlSource.getBoundSql(parameterObject);
  count = getCount(connection, mappedStatement, parameterObject, newBoundSql);
} else if (sqlSource instanceof MicaRawSqlSource) {
  String rawSql = ((MicaRawSqlSource) sqlSource).getRawSql();
  DynamicContext context = new DynamicContext(configuration, parameterObject);
  // 生成 count sql,带 #{xxx} 变量的 sql
  String countSql = PagerUtils.count(rawSql, dbType);
  SqlSource newSqlSource = sqlSourceParser.parse(countSql, parameterType, context.getBindings());
  BoundSql newBoundSql = newSqlSource.getBoundSql(parameterObject);
  count = getCount(connection, mappedStatement, parameterObject, newBoundSql);
} else {
  throw new IllegalArgumentException("不支持的 sql 分页形式,请使用 xml 或者注解");
}

五、结论

整个老服务通过切换到 mica(深度定制)的微服务架构(演示环境仅仅在单服务低内存配置)之后速度提升效果明显,当然后面我们还会继续进行优化。

到此这篇关于SpringBoot使用 druid 连接池来优化分页语句的文章就介绍到这了,更多相关SpringBoot druid 连接池分页内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 使用Springboot封装好的发送post请求的工具类

    使用Springboot封装好的发送post请求的工具类

    本文介绍了在Springboot中封装发送HTTP请求的工具类,并提供了普通的HTTP请求工具类代码和Response类的使用示例,这些工具类可为开发者提供便利性和参考价值,帮助提高开发效率
    2024-09-09
  • spring-kafka使消费者动态订阅新增的topic问题

    spring-kafka使消费者动态订阅新增的topic问题

    这篇文章主要介绍了spring-kafka使消费者动态订阅新增的topic问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • springboot整合shiro实现记住我功能

    springboot整合shiro实现记住我功能

    这篇文章主要介绍了springboot整合shiro实现记住我功能,配置类 ShiroConfig,通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2021-10-10
  • Java实现读取TXT和CSV文件内容

    Java实现读取TXT和CSV文件内容

    这篇文章主要为大家详细介绍了如何利用Java语言实现读取TXT和CSV文件内容的功能,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2023-02-02
  • Java正则表达式(匹配、切割、替换、获取)等方法

    Java正则表达式(匹配、切割、替换、获取)等方法

    这篇文章主要介绍了Java正则表达式(匹配、切割、替换、获取)等方法的相关资料,需要的朋友可以参考下
    2017-06-06
  • 深入理解Spring AOP

    深入理解Spring AOP

    这篇文章主要介绍了深入理解Spring AOP,详细的介绍了spring aop的具体实现与理论
    2017-01-01
  • Spring 5.0集成log4j2日志管理的示例代码

    Spring 5.0集成log4j2日志管理的示例代码

    本篇文章主要介绍了Spring 5.0集成log4j2日志管理的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • Java前端Layer.open.btn验证无效解决方法

    Java前端Layer.open.btn验证无效解决方法

    在本篇文章里我们给大家整理了一篇关于Java前端Layer.open.btn验证无效解决方法以及实例代码,需要的朋友们可以参考学习下。
    2019-09-09
  • Windows环境使用bat脚本启动Java服务的过程

    Windows环境使用bat脚本启动Java服务的过程

    Java项目一般会被打包成jar后启动,在windows系统中可以通过终端窗口cmd启动jar包,即在jar包所在的目录中打开cmd,或在cmd中进入到jar包目录,这篇文章主要介绍了Windows环境使用bat脚本启动Java服务,需要的朋友可以参考下
    2023-08-08
  • 详解SpringBoot中使用JPA作为数据持久化框架

    详解SpringBoot中使用JPA作为数据持久化框架

    这篇文章主要介绍了SpringBoot中使用JPA作为数据持久化框架的相关知识,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-03-03

最新评论