How do you configure the data source connection pool for Tomcat?
Configuring a data source connection pool in Tomcat requires configuration in the context.xml file. The following are the configuration steps:
Open the conf folder in the installation directory of Tomcat, and locate the context.xml file.
Add the data source configuration in the context.xml file, with an example configuration as shown below:
<Resource name="jdbc/yourDataSourceName" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="yourUsername" password="yourPassword" driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false"
validationQuery="SELECT 1" testOnBorrow="true"/>
The ‘name’ property represents the JNDI name of the data source, while ‘maxTotal’, ‘maxIdle’, and ‘maxWaitMillis’ respectively indicate the maximum total connections, maximum idle connections, and maximum wait time of the connection pool. ‘username’ and ‘password’ are for the database username and password, ‘driverClassName’ is the class name of the database driver, ‘url’ is the database connection address, ‘validationQuery’ is the query statement for validation, and ‘testOnBorrow’ indicates whether validation should be performed when retrieving a connection from the pool.
Put the jar file of the database driver into the lib folder of Tomcat.
4. Configure the JNDI name of the data source in the web.xml file, with an example configuration as follows:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/yourDataSourceName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
In the application, retrieve a data source connection using the JNDI name. Here is an example code.
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/yourDataSourceName");
Connection conn = ds.getConnection();
The above are the steps for configuring a data source connection pool in Tomcat, with this configuration you can manage database connections in your application using a connection pool.