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解决跨域的5种方式小结

    SpringBoot解决跨域的5种方式小结

    在项目开发中,时常会遇到跨域问题,本文主要介绍了五种解决跨域的方法,使用最多的是第三种,需要的朋友们下面随着小编来一起学习学习吧
    2021-06-06
  • servlet实现文件上传、预览、下载、删除功能

    servlet实现文件上传、预览、下载、删除功能

    这篇文章主要为大家详细介绍了servlet实现文件上传、预览、下载、删除功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-09-09
  • Spring Cloud Config分布式配置中心使用介绍详解

    Spring Cloud Config分布式配置中心使用介绍详解

    分布式配置中心应用场景 往往,我们使用配置文件管理⼀些配置信息,比如application.yml 单体应用架构:配置信息的管理、维护并不会显得特别麻烦,手动操作就可以,因为就一个工程
    2022-09-09
  • Java字符串转时间简单示例代码

    Java字符串转时间简单示例代码

    这篇文章主要给大家介绍了关于Java字符串转时间的相关资料,在Java中字符和字符串常常需要相互转化,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
    2023-08-08
  • Springboot中的自定义拦截器及原理详解

    Springboot中的自定义拦截器及原理详解

    这篇文章主要介绍了Springboot中的自定义拦截器及原理详解,拦截器主要是用于在用户请求控制中,对于请求识别,鉴权,以及区分资源是否可以被目标方法调用的安全机制,需要的朋友可以参考下
    2023-12-12
  • Spring整合quartz做定时任务的示例代码

    Spring整合quartz做定时任务的示例代码

    这篇文章主要介绍了在spring项目使用quartz做定时任务,首先我这里的项目已经是一个可以跑起来的完整项目,web.xml里面的配置我就不贴出来了,具体实例代码跟随小编一起看看吧
    2022-01-01
  • 基于Java事件监听编写一个中秋猜灯谜小游戏

    基于Java事件监听编写一个中秋猜灯谜小游戏

    众所周知,JavaSwing是Java中关于窗口开发的一个工具包,可以开发一些窗口程序,然后由于工具包的一些限制,导致Java在窗口开发商并没有太多优势,不过,在JavaSwing中关于事件的监听机制是我们需要重点掌握的内容,本文将基于Java事件监听编写一个中秋猜灯谜小游戏
    2023-09-09
  • Mybatis velocity脚本的使用教程详解(推荐)

    Mybatis velocity脚本的使用教程详解(推荐)

    很多朋友不清楚在mybatis可以使用各种脚本语言来定义Mapper文件里面的动态SQL;目前mybatis支持的脚本语言有XML(默认的);Velocity和Freemarker三种。下面通过本文给大家介绍Mybatis velocity脚本的使用,一起看看吧
    2016-11-11
  • java面试题解LeetCode27二叉树的镜像实例

    java面试题解LeetCode27二叉树的镜像实例

    这篇文章主要为大家介绍了java面试题解LeetCode27二叉树的镜像实例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-01-01
  • Java ​​​​​​​HashMap遍历方法汇总

    Java ​​​​​​​HashMap遍历方法汇总

    这篇文章主要介绍了Java ​​​​​​​HashMap遍历方法汇总,HashMap 的遍历方法有很多种,不同的 JDK 版本有不同的写法,下文关于其遍历方法总结需要的小伙伴可以参考一下
    2022-05-05

最新评论