我想使用与Java的池连接(因为每个线程创建一个连接的成本很高)所以我正在使用该MysqlConnectionPoolDataSource()对象.我在线程中持久化我的数据源.所以,我只在整个应用程序中使用一个数据源,如下所示:
startRegistry(); // creates an RMI registry for MySQL
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setUser("username");
dataSource.setPassword("password");
dataSource.setServerName("serverIP");
dataSource.setPort(3306);
dataSource.setDatabaseName("dbname");
InitialContext context = createContext(); // Creates a context
context.rebind("MySQLDS", dataSource);
Run Code Online (Sandbox Code Playgroud)
现在我创建了自己的数据源,我在每个单独的线程中执行以下操作:
PooledConnection connect = dataSource.getPooledConnection();
Connection sqlConnection = connect.getConnection();
Statement state = sqlConnection.createStatement();
ResultSet result = state.executeQuery("select * from someTable");
// Continue processing results
Run Code Online (Sandbox Code Playgroud)
我想我很困惑的是调用dataSource.getPooledConnection();
是否真的取得了汇集连接? 这个线程安全吗?我注意到PooledConnection有像notify()和wait()这样的方法......这意味着我不认为它正在做我认为它正在做的事情......
此外,何时以及如何释放连接?
我想知道滚动自己是否更有利,因为那时我会更熟悉一切,但我真的不想在这种情况下重新发明轮子:).
谢谢你
经过一段时间的运行后,当我用至少20个浏览器标签同时访问servlet来测试我的servlet时,我遇到了这个错误:
java.sql.SQLException:[tomcat-http - 10]超时:池为空.无法在10秒内获取连接,无法使用[size:200; 忙:200; 空闲:0; lastwait:10000].
这是以下的XML配置:
<Resource name="jdbc/MyAppHrd"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="200"
minIdle="10"
maxWait="10000"
initialSize="200"
removeAbandonedTimeout="120"
removeAbandoned="true"
logAbandoned="false"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="sa"
password="password"
driverClassName="net.sourceforge.jtds.jdbc.Driver"
url="jdbc:jtds:sqlserver://192.168.114.130/MyApp"/>
Run Code Online (Sandbox Code Playgroud)
可能是什么问题呢?
更新:Java代码:
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log LOGGER = LogFactory.getLog(MyServlet.class);
private void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
CallableStatement stmt = null;
ResultSet rs = null;
Connection conn = null;
try …Run Code Online (Sandbox Code Playgroud)