您好,欢迎访问一九零五行业门户网

MySQL JDBC PrepareStatement基本的两种模式&客户端空间占用

关于预编译(preparestatement),对于所有的jdbc驱动程序来讲,有一个共同的功能,就是“ 防止sql注入 ”,类似oracle还有一种“ 软解析 ”的概念,它非常适合应用于oltp类型的系统中。 在jdbc常见的操作框架中,例如ibatis、jdbctemplate这些框架对jdbc操
关于预编译(preparestatement),对于所有的jdbc驱动程序来讲,有一个共同的功能,就是“防止sql注入”,类似oracle还有一种“软解析”的概念,它非常适合应用于oltp类型的系统中。
在jdbc常见的操作框架中,例如ibatis、jdbctemplate这些框架对jdbc操作时,默认会走预编译(jdbctemplate如果没有传递参数,则会走createstatement),这貌似没有什么问题。不过在一个应用中发现了大量的预编译对象导致频繁gc,于是进行了源码上的一些跟踪,写下这篇文章,这里分别从提到的几个参数,以及源码中如何应用这几个参数来说明。
看看有那些参数:
mysql jdbc是通过其driver的connenct方法获取到连接,然后可以将连接参数设置在jdbc url或者properties中,它会根据这些参数来创建一个connection,简单说来就是将这些参数解析为k-v结构,交给connection的对象来解析,connection会将它们解析为自己所能识别的许多属性中,这个属性的类型为:connectionproperty,当然有许多子类来实现不同的类型,例如:booleanconnectionproperty、integerconnectionproperty是处理不同参数类型的。
这些参数会保存在connection对象中(在源码中,早期的版本,源码的类名就叫:com.mysql.jdbc.connection,新版本的叫做:com.mysql.jdbc.connectionimpl,抽象了接口与实现类,这里统一称connection的对象);具体是保存在这个connection的父类中,这里将几个与本题相关的几个参截取出来,如下所示:
private booleanconnectionproperty cachepreparedstatements = new booleanconnectionproperty( cacheprepstmts, //$non-nls-1$ false, messages.getstring(connectionproperties.cacheprepstmts), //$non-nls-1$ 3.0.10, performance_category, integer.min_value); //$non-nls-1$private integerconnectionproperty preparedstatementcachesize = new integerconnectionproperty( prepstmtcachesize, 25, 0, integer.max_value, //$non-nls-1$ messages.getstring(connectionproperties.prepstmtcachesize), //$non-nls-1$ 3.0.10, performance_category, 10); //$non-nls-1$private integerconnectionproperty preparedstatementcachesqllimit = new integerconnectionproperty( prepstmtcachesqllimit, //$non-nls-1$ 256, 1, integer.max_value, messages.getstring(connectionproperties.prepstmtcachesqllimit), //$non-nls-1$ 3.0.10, performance_category, 11); //$non-nls-1$private booleanconnectionproperty detectserverpreparedstmts = new booleanconnectionproperty( useserverprepstmts, //$non-nls-1$ false, messages.getstring(connectionproperties.useserverprepstmts), //$non-nls-1$ 3.1.0, misc_category, integer.min_value); //$non-nls-1$
找到这个通常要看看获取它的方法名,显然实际执行的时候,一般用方法来获取,而且这里的类型是private,也就是子类不可见,直接访问如果不通过变通手段访问不到;也许我们搞java的第一眼看到的就是就是属性名的get方法嘛,有些时候mysql这个该死的就是不按照常规思路走,例如它对属性:“detectserverpreparedstmts”的获取方法是:“getuseserverpreparedstmts()”,如下图:
好吧,不关注它的屌丝做法了,来继续关注正题。
来看看preparestatement初始化与编译过程:
要预编译,自然是通过connection去做的,默认调用的预编译参数是这样一个方法:
public java.sql.preparedstatement preparestatement(string sql) throws sqlexception { return preparestatement(sql, java.sql.resultset.type_forward_only, java.sql.resultset.concur_read_only);}
这个方法貌似还看不出什么东西,但是可以稍微留意下发现默认值是什么,继续往下走,走到一个重载方法中,这个重载方法body部分太长了,看起来费劲,说起来难,经过梳理,我将它简化一下,如下图所示:
这里将逻辑分解为两个大板块:一个为com.mysql.jdbc.serverpreparedstatement,一个是默认的,反过来讲就是如果是服务器端的statement,处理类的类名一眼就能看出来。
那么什么时候会走服务器端的preparestatement呢?服务器端的preparestatement与普通的到底有什么区别呢?先看第一个问题,以下几条代码是进入逻辑的关键:
boolean canserverprepare = true;string nativesql = getprocessescapecodesforprepstmts() ? nativesql(sql): sql;if (this.useserverpreparedstmts && getemulateunsupportedpstmts()) { canserverprepare = canhandleasserverpreparedstatement(nativesql);}if (this.useserverpreparedstmts && canserverprepare) { ....使用serverpreparestatement}
也就是判定逻辑是基于“useserverpreparedstmts”、“canserverprepare”这两个参数决定的,而“useserverpreparedstmts”我们可以将对应的参数设置为true即可,参数对应到那里呢?在第一个参数列表图中,就对应到:“detectserverpreparedstmts”,而在jdbc url上需要设置的是:“useserverprepstmts”,定义如
private booleanconnectionproperty detectserverpreparedstmts = new booleanconnectionproperty( useserverprepstmts, //$non-nls-1$ false, messages.getstring(connectionproperties.useserverprepstmts), //$non-nls-1$ 3.1.0, misc_category, integer.min_value); //$non-nls-1$
而另一个参数canserverprepare并非默认,它虽然被初始化设置了true,但是getemulateunsupportedpstmts()这个方法跟踪进去也会发现默认是true(当然可以通过设置参数将其设置为false),对应到代码中,参数canserverprepare的值将由方法:canhandleasserverpreparedstatement(string)来决定,跟踪进去会发现,首先只考虑“select、update、delete、insert、replace”几种语法规则,也就是如果不是这几种就直接返回false了。另外会对参数limit后面7位做一个判定是否有逗号、?这些符号,如果有这些就返回false了,对于这7位一直很纳闷,因为limit后面7位最多包含一个占位符,而分页最少2个。
这里说明这些就只想说明,“并不一定将useserverprepstmts设置为true,就一定会采用服务器端的preparestatement”;这假设已经采用了服务器端的,它做了什么呢?
pstmt = serverpreparedstatement.getinstance(this, nativesql, this.database, resultsettype, resultsetconcurrency);
这个是代码中的关键,跟踪进去,你会发现它这个动作,会向服务器端发送sql,很明显的,这里还没有执行sql,只是预编译,就已经将sql交给服务器端,那么后面只需要拿到相应的状态标识给服务器端参数即可。
另外,这个里面还有一层是:getcachepreparedstatements(),这个参数就是对应到上图中设置的“cacheprepstmts”,它的定义如下所示:
private booleanconnectionproperty cachepreparedstatements = new booleanconnectionproperty( cacheprepstmts, //$non-nls-1$ false, messages.getstring(connectionproperties.cacheprepstmts), //$non-nls-1$ 3.0.10, performance_category, integer.min_value); //$non-nls-1$
它将首先预判定是否将sql cache到一个内存区域中,然后再内部创建serverpreparestatement,如果创建失败则也调用client的,并且在失败的时候put到serversidestatementcheckcache这个里面(这里可以看到出来是基于sql的k-v结构,k肯定是sql了,value等下来看),成功的值发现做了一个:
if (sql.length()
这个判定语句很明显是判定sql长度的,也就是sql长度低于某个值就设置这个参数,这个getpreparedstatementcachesqllimit()就是来自第一个图中的:preparedstatementcachesqllimit参数,jdbc url参数是:prepstmtcachesqllimit,它的默认值是256,如下所示:
private integerconnectionproperty preparedstatementcachesqllimit = new integerconnectionproperty( prepstmtcachesqllimit, //$non-nls-1$ 256, 1, integer.max_value, messages.getstring(connectionproperties.prepstmtcachesqllimit), //$non-nls-1$ 3.0.10, performance_category, 11); //$non-nls-1$
但是这个iscache仅仅是设置一个boolean值,那里做了cache呢?没有简单做任何cache,仅仅看到是失败的会cache,它到底在哪里有用呢,跟踪到内部会在statement发生close的时候有用:
public synchronized void close() throws sqlexception { if (this.iscached && !this.isclosed) { clearparameters(); this.isclosed = true; this.connection.recachepreparedstatement(this); return; } realclose(true, true);}
这个:recachepreparedstatement()方法最终也会调用:serversidestatementcache来讲编译信息设置进去,也就是这个cache始终在客户端,而服务器端preparestatement只是代表了谁来编译这个sql语句的问题。
也许对clientpreparestatement感兴趣,就去看看它的代码,同样这个代码很长,我也简单简化了下逻辑如下图所示:
这个逻辑基本与serverpreparestatement内部的逻辑差不多,唯一的区别就是这个是显式做了lru算法,而这个lru是一是一种最简单的最近最久未使用方式,将最后一个删掉,将现在这个写进去,它同样也有getcachepreparedstatements()、getpreparedstatementcachesqllimit()来控制是否做cache操作,也同样用了一个k-v结构来做cache,这个k-v结构,通过connection的初始化方法:initializedriverproperties(properties)间接调用:createpreparedstatementcaches()完成初始化,可以看到他会被初始化为一个hashmap结构,较早的版本会创建多个类似大小的对象出来。
好了,现在来看问题,一个hashmap不足以造成多少问题,因为有lru队列来控制长度,但是看代码中你会发现它没控制并行处理,hashmap是非线程安全的,那么为啥mysql jdbc没出问题呢?因为你会发现这个hashmap完全绑定到connection对象上,成为connection对象的一个属性,连接池分配的时候没见过会将一个connection同时分配给两个请求的,因此它将并发的问题交给了连接池来解决,自己认为线程都是安全的,反过来,如果你自己去并行同一个connection可能会有问题。
继续回到问题上来,每个connection都可能cache几十个上百个statement对象,那么一个按照线上数据源的配置,也就配置5~10个是算比较大的了,也就最多上千个对象,jvm配置都是多少g的空间,几千个对象能造成什么问题?
于是我们来看他cache了什么,主要是普通的preparestatement,里面的代码发现编译完后返回了一个parseinfo类型对象,然后将它作为value写入到hashmap中,它是一个preparestatement的内部类,它的定义如下所示:
class parseinfo { char firststmtchar = 0; boolean foundlimitclause = false; boolean foundloaddata = false; long lastused = 0; int statementlength = 0; int statementstartpos = 0; byte[][] staticsql = null;}
我们可以搬着手指头算下,对象头部、属性、padding大致占用的空间(当然是在64bit),发现也不大,而最关键的是这个二维数组,byte[][]staticsql,它占用多大,经过代码跟踪我们发现它与占位符的个数相关,也就是参数中的“?”个数,这个个数将决定第一维的大小,而sql中的每个字节将填写到数组的第二维。
java中没有绝对的二维数组,都是通过一维数组虚拟出来的,而第一维本身也是一个引用数组,占用的空间自然很大,参数个数自然和业务表相关,至少会有“增、删、改、查”,查和删其实占位符较少,而相应的业务系统写操作是十分多的,因此参数个数用15~20个来估算不算过分,而sql长度用200来估算也不过分,通过简单估算,这个空间将会是原来sql的2~3倍甚至于更多,但是也不至于有问题呀?
再回头看看,一个hashmap里面的key、value、next、hash几个会形成一个新的对象,而key是sql,自然会占用sql的空间大小,vaue是好几倍的sql空间,其余的再抛开hashmap本身数组的利用率极低外,这里可能sql的宽度会上k的占用,不过算起来还是不对,因为就算是1000k,也只有1m,再放大几倍也只有几m的空间。
想不通了,后来一个小情况得到了提醒,那就是数据库是分布式的,分布式数据库的连接池配置底层会针对每一个访问过的数据库建立初始化大小的连接数,那么自然的,这个数据应当乘以数据库的个数,该应用存在上百个数据库,那么自然的1m到几m的空间,就上升到一百到几百m,不过也不至于有这么大的问题,因为基本内存都用g来衡量的,再细探,数据库还存在读写分流,也就是部分流量会分配到备库上,而一个数据库会有多个备库,自然的读流量只要访问过也会在备库上建立同样的connection,即使你用得不多,那么自然的空间还要乘以一套库的个数,例如乘以4,那么这个空间就完全有可能占用得非常大,理论上这些数据就是这样来的了。
回头再来看看parseinfo到底在什么时候用,普通的preparestatement(即客户端的),到底是怎么与服务器端通信的,我们用一个常见的executequery查询语句来看代码,它内部通过一个叫:buffer sendpacket = fillsendpacket();这个方法获取到要与mysql服务器端通信的package的buffer,它的代码是这样的:
protected buffer fillsendpacket() throws sqlexception { return fillsendpacket(this.parametervalues, this.parameterstreams, this.isstream, this.streamlengths);}
发现又调用了一个该死的重载方法,但是知道了传入的是参数列表parametervalues,而重载方法中,这个方法入口参数的名字变成了:batchedparameterstrings,说明重载方法是兼容批处理的,只是单个语句传入的参数可能在里面只循环一次而,跟踪进去,发现一段很重要的循环的地方是这样的:
for (int i = 0; i
这个循环看到每次都会将staticsqlstrings拼接一次,然后再拼接一个参数,这个就是一个byte[][]格式,而它的赋值就是来源于parseinfo,在方法:preparestatement中的initializefromparseinfo()中有相应的说明。
也就是说他用的就是parseinfo中的内容,而那个内容分析过,与占位符相关,其实就是将sql从占位符的位置拆分开,然后实际运行时,再通过实际的参数拼接起来,这个就是文本协议,虽然它是预编译,但是它也是拼接sql出来的。
此时我们很好奇的问题,既然都是拼接sql,它如何防止sql注入呢?那么自然是看看setstring方法到底干了啥,一下是它的源码:
public void setstring(int parameterindex, string x) throws sqlexception { // if the passed string is null, then set this column to null if (x == null) { setnull(parameterindex, types.char); } else { checkclosed(); int stringlength = x.length(); if (this.connection.isnobackslashescapesset()) { // scan for any nasty chars boolean needshexescape = isescapeneededforstring(x, stringlength); if (!needshexescape) { byte[] parameterasbytes = null; stringbuffer quotedstring = new stringbuffer(x.length() + 2); quotedstring.append('\''); quotedstring.append(x); quotedstring.append('\''); if (!this.isloaddataquery) { parameterasbytes = stringutils.getbytes(quotedstring.tostring(), this.charconverter, this.charencoding, this.connection.getservercharacterencoding(), this.connection.parserknowsunicode()); } else { // send with platform character encoding parameterasbytes = quotedstring.tostring().getbytes(); } setinternal(parameterindex, parameterasbytes); } else { byte[] parameterasbytes = null; if (!this.isloaddataquery) { parameterasbytes = stringutils.getbytes(x, this.charconverter, this.charencoding, this.connection.getservercharacterencoding(), this.connection.parserknowsunicode()); } else { // send with platform character encoding parameterasbytes = x.getbytes(); } setbytes(parameterindex, parameterasbytes); } return; } string parameterasstring = x; boolean needsquoted = true; if (this.isloaddataquery || isescapeneededforstring(x, stringlength)) { needsquoted = false; // saves an allocation later stringbuffer buf = new stringbuffer((int) (x.length() * 1.1)); buf.append('\''); // // note: buf.append(char) is _faster_ than // appending in blocks, because the block // append requires a system.arraycopy().... // go figure... // for (int i = 0; i
可以发现,它将传入的参数,进行了特殊字符的转义处理,另外就是在字符串的两边加上了单引号,也就是这与mysql将sql转义后传送给服务器端的东西,也就是最终传送的不是分解sql与参数,而是拼接sql,只是通过转义防止sql注入。
在mysql jdbc中,其实还有许多类似的伪转换,例如批处理,它使用循环来完成的,不过它也算满足了jdbc驱动的基本规范。
另外,在mysql分布式数据库上,分表是非常多的,每个物理分表都会有至少好几个sql,即使每个库下面也会有许多,那么配置几十个cache,它的命中率到底有多少呢?而即便是一个库下面的多个connection,他们的cache都是彼此独立的,意味着库越多、同一个库下面的表越多、业务逻辑越复杂,这样一个connection需要多少cache才能达到想要的效果呢?而cache后的结果是占用更多的jvm空间,而且是许多的jvm空间,即使内存可以放得下,在现在的jvm中,只要做发生full  gc也会去扫描它们、移动它们。但是反过来,解析这个sql语句只是解析出占位符,纯cpu密集型,而且次数相对cpu来讲就是小儿科,一个普通sql可能就是1us的时间,我们没有必要跟jvm过不去,做费力不讨好的事情,因为本身就很土鳖了,再土点不就完蛋了吗。

其它类似信息

推荐信息