相信使用MySQL的同学都配置过它的JDBC驱动,多数人会直接从哪里贴一段URL过来,然后稍作修改就上去了,对应的连接池配置也是一样的,很少有人会去细想这每一个参数都是什么含义。今天我们就来聊两个比较常见的配置——是否要开启autoReconnect和是否缓存PreparedStatement。
一、autoReconnect=true真的好用么?
笔者看到过很多MySQL的URL里都是这样写的,复制过来改改IP、端口和库名就能用了:
jdbc:mysql://xxx.xxx.xxx.xxx:3306/xxx?autoReconnect=true&...
从字面上看挺好的,在连接断开后还会自动重连,加之MySQL有8小时自动断开连接的特性,在断开后连接会重连,多好的功能呀。但是如果你去阅读一下MySQL Connect/J开发手册的相关章节,就会看到官方是这么说明的:
The use of this feature is not recommended, because it has side effects related to session state and data consistency when applications don't handle SQLExceptions properly, and is only designed to be used when you are unable to configure your application to handle SQLExceptions resulting from dead and stale connections properly.
简单来说,不推荐开启这个特性,因为有副作用,在没有正确处理SQLException时容易造成会话状态和数据一致性的问题。</