SpringBoot使用 druid 连接池来优化分页语句
一、前言
一个老系统随着数据量越来越大,我们察觉到部分分页语句拖慢了我们的速度。
鉴于老系统的使用方式,不打算使用pagehelper和mybatis-plus来处理,加上系统里使用得是druid连接池,考虑直接使用druid来优化。
二、老代码
老代码是使用得一个mybatis插件进行的分页,分页的核心代码如下:
//记录统计的sql StringcountSql="selectcount(0)from("+sql+")tmp_count"; PreparedStatementcountStmt=connection.prepareStatement(countSql); BoundSqlcountBS=newBoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject); setParameters(countStmt,mappedStatement,countBS,parameterObject);
在原始的sql外面包装了一个countsql,当然很多插件都是这样做的。
三、druid的PagerUtil
示例sql(有比较复杂的坐标计算)
SELECTg.* ,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)ASdistancecd ,t.agentname,t.agentlogo,t.compaddress FROMt_bas_integral_goodsg LEFTJOINt_bas_agenttONg.agentid=t.AGENTID WHEREt.AGENTTYPE='2' ANDt.pass='0' ANDt.dl_type='4' ANDg.type=0 ORDERBYdistancecdASC
使用Druid生成countsql:
StringcountSql=PagerUtils.count(sql,DbType.mysql); System.out.println(countSql);
输出:
SELECTCOUNT(*) FROMt_bas_integral_goodsg LEFTJOINt_bas_agenttONg.agentid=t.AGENTID WHEREt.AGENTTYPE='2' ANDt.pass='0' ANDt.dl_type='4' ANDg.type=0
我们可以看到优化后的countsql变得十分简洁,坐标计算的都已经丢弃掉。注意:PagerUtil还有limit方法用来生成limit语句,感兴趣的同学可以自行试验。
四、改造mybatis分页插件
4.1踩坑之路
看到上面druidPagerUtilscount的优化效果,立马开始改造起来,起初只改掉了countSql,
StringcountSql=PagerUtils.count(sql,dbType); PreparedStatementcountStmt=connection.prepareStatement(countSql); BoundSqlcountBS=newBoundSql(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*fromxxxwheretype=#{type}orderbyxx
输出:
SELECTCOUNT(*) FROMxxx WHEREtype=#{type}
完美!!!4.2继续踩坑
然而直接在Mapper上注解的sql还是有问题,拿不到原始的sql,debug发现RawSqlSource在构造器里就将sql处理成了?号挂参的形式。
@Select("select*fromxxxwheretype=#{type}orderbyxx") Objecttest(@Param("type")Stringtype);
那么我只能看看能不能扩展它,我找到了它是在XMLLanguageDriver里进行初始化,这下好办了,因为我之前扩展过XMLLanguageDriver,它是可以自定义配置的。于是我重写了RawSqlSource,添加上了包含mybatis参数占位符(#{})的rawSql字段。
/** *原始sql,用于方便druid工具进行分页 * *@authorL.cm */ publicclassMicaRawSqlSourceimplementsSqlSource{ privatefinalStringrawSql; privatefinalSqlSourcesqlSource; publicMicaRawSqlSource(Configurationconfiguration,SqlNoderootSqlNode,Class>parameterType){ this(configuration,getSql(configuration,rootSqlNode),parameterType); } publicMicaRawSqlSource(Configurationconfiguration,Stringsql,Class>parameterType){ SqlSourceBuildersqlSourceParser=newSqlSourceBuilder(configuration); Class>clazz=parameterType==null?Object.class:parameterType; this.rawSql=sql; this.sqlSource=sqlSourceParser.parse(sql,clazz,newHashMap<>()); } //...... }
自此全部逻辑已经走通,我们再来看看我们的PagePlugin核心代码:
//进行分页 Configurationconfiguration=mappedStatement.getConfiguration(); SqlSourceBuildersqlSourceParser=newSqlSourceBuilder(configuration); Class>parameterType=parameterObject.getClass(); Connectionconnection=(Connection)invocation.getArgs()[0]; //1.对sql进行判断,如果没有?号,则直接处理 StringboundRawSql=boundSql.getSql(); if(boundRawSql.indexOf(CharPool.QUESTION_MARK)==-1){ //不包含?号 StringcountSql=PagerUtils.count(boundRawSql,dbType); SqlSourcenewSqlSource=sqlSourceParser.parse(countSql,parameterType,newHashMap<>()); BoundSqlnewBoundSql=newSqlSource.getBoundSql(parameterObject); intcount=getCount(connection,mappedStatement,parameterObject,newBoundSql); StringBuildersqlBuilder=newStringBuilder(boundRawSql); Pagepage=getPageParam(parameterObject,sqlBuilder,count); StringpageSql=generatePageSql(sqlBuilder.toString(),dbType,page); //将分页sql语句反射回BoundSql. setField(boundSql,"sql",pageSql); returninvocation.proceed(); } //2.按SqlSource进行解析 SqlSourcesqlSource=mappedStatement.getSqlSource(); //xml中的动态sql intcount; if(sqlSourceinstanceofDynamicSqlSource){ SqlNoderootSqlNode=PagePlugin.getField(sqlSource,"rootSqlNode"); DynamicContextcontext=newDynamicContext(configuration,parameterObject); rootSqlNode.apply(context); //生成countsql,带#{xxx}变量的sql StringcountSql=PagerUtils.count(context.getSql(),dbType); SqlSourcenewSqlSource=sqlSourceParser.parse(countSql,parameterType,context.getBindings()); BoundSqlnewBoundSql=newSqlSource.getBoundSql(parameterObject); count=getCount(connection,mappedStatement,parameterObject,newBoundSql); }elseif(sqlSourceinstanceofMicaRawSqlSource){ StringrawSql=((MicaRawSqlSource)sqlSource).getRawSql(); DynamicContextcontext=newDynamicContext(configuration,parameterObject); //生成countsql,带#{xxx}变量的sql StringcountSql=PagerUtils.count(rawSql,dbType); SqlSourcenewSqlSource=sqlSourceParser.parse(countSql,parameterType,context.getBindings()); BoundSqlnewBoundSql=newSqlSource.getBoundSql(parameterObject); count=getCount(connection,mappedStatement,parameterObject,newBoundSql); }else{ thrownewIllegalArgumentException("不支持的sql分页形式,请使用xml或者注解"); }
五、结论
整个老服务通过切换到mica(深度定制)的微服务架构(演示环境仅仅在单服务低内存配置)之后速度提升效果明显,当然后面我们还会继续进行优化。
到此这篇关于SpringBoot使用druid连接池来优化分页语句的文章就介绍到这了,更多相关SpringBootdruid连接池分页内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!