对于数据库连接超时问题,是一个经典问题,不外乎两种解决办法。一种是配置数据库本身的连接时长。一种是通过软件自身来解决。显然是第二种主法是最佳选择。对于MyBatis,经常使用的配置如下:
- <environments default="product">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&" />
- <property name="username" value="root"/>
- <property name="password" value="zhiyisoft"/>
- </dataSource>
- </environment>
- <environment id="product">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/prometheus?useUnicode=true&characterEncoding=utf8" />
- <property name="username" value="root"/>
- <property name="password" value="zhiyisoft"/>
- </dataSource>
- </environment>
- </environments>
这里需要重点关注的是product这个环境,通常我们都使用POOLED这个自带的DataSource,但上面的这种简单配置,不会对连接超时做检查。再配置上以下属性即可:
- <property name="poolPingEnabled" value="true"/>
- <property name="poolPingQuery" value="select 10000 as salary"/>
- <property name="poolPingConnectionsNotUsedFor" value="14400000"/>
当然最重要的是poolPingEnabled这个属性,它们的含义如下:- poolPingEnabled
- poolPingQuery
- poolPingConnectionsNotUsedFor
POOLED这个DataSource别名实际上对应的是这个类:org.apache.ibatis.datasource.pooled.PooledDataSource
下面列出该类的属性声明:
- private final PoolState state = new PoolState(this);
- private final UnpooledDataSource dataSource;
- // OPTIONAL CONFIGURATION FIELDS
- protected int poolMaximumActiveConnections = 10;
- protected int poolMaximumIdleConnections = 5;
- protected int poolMaximumCheckoutTime = 20000;
- protected int poolTimeToWait = 20000;
- protected String poolPingQuery = "NO PING QUERY SET";
- protected boolean poolPingEnabled = false;
- protected int poolPingConnectionsNotUsedFor = 0;
- private int expectedConnectionTypeCode;
不过,有些参数也需要数据库服务器配合,以mysql为例,其中max_connections和max_user_connections是到至关重要的。分别代表整个服务器的最大连接数和单数据库允许的最大用户连接数。在mysql中可以在my.cnf中的[mysqld]下,以这样的格式来配置:
set-variable=max_user_connections=300
阅读(8923) | 评论(0) | 转发(0) |