I'm using the tomcat connection pool via JNDI resources.
In the context.xml
:
<Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource"
username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
maxActive="1000" maxIdle="100" maxWait="10000"
url="jdbc:mysql://localhost:3306/mydatabase"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" />
In web.xml
:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
From the java classes in which I need db connections, I do this lookup:
Context initContext = new InitialContext();
DataSource ds = (DataSource)initContext.lookup("java:/comp/env/jdbc/mydb");
My first doubt is the DataSource type. Is it the same using javax.sql.DataSource
or org.apache.tomcat.jdbc.pool.DataSource
?
Moreover, sometimes I obtain a "Too many connections" error. I've read many stackoverflow question/answers about this, but I don't succeed in understanding where the problem could be.
I have followed the tomcat docs, and I close properly result sets, statements and connection.
EDIT
My tomcat version is 7.0.26. So there should be a bug (see link suggested by informatik01 user)
If you put the JDBC resource in the $CATALINA_HOME/conf/context.xml it loads the resource for every single webapp you have deployed. (Which can mean a huge number of connections) If you move that resource to META-INF/context.xml of your webapp it will only load when that specific webapp is deployed. http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html
It could also be that you have way too many maxActive and maxIdle.
javax.sql.DataSource
is an interface and org.apache.tomcat.jdbc.pool.DataSource
is a class. I am not sure if tomcat permits us to directly instantiate org.apache.tomcat.jdbc.pool.DataSource
. If yes, you can use any of these.
The connection related error could be due to
maxActive="1000" maxIdle="100" maxWait="10000"
in your tomcat configuration file.
Set it to maxActive="10" maxIdle="10" maxWait="10"
- 10 number of active connections, 10 number of idle connections with a maximum 10 seconds wait time.
您可能需要增加mysql的最大连接数,默认最大值为151。
确保没有资源泄漏:示例java.sql.Connection未关闭
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.