How should the Tomcat connection pool be configured?

To set up Tomcat connection pool, you can follow these steps: 1. Locate the context.xml file in the conf folder of Tomcat. 2. Add the following configuration to the context.xml file.

<Resource name="jdbc/yourDataSourceName" auth="Container" type="javax.sql.DataSource"

maxTotal="100" maxIdle="30" maxWaitMillis="10000"

               username="yourUsername" password="yourPassword"

               driverClassName="yourDriverClassName" url="yourJDBCUrl"/>

3. Explanation of the above configuration options: name defines the name of the data source. auth specifies the authentication method, usually Container. type specifies the data source type as javax.sql.DataSource. maxTotal is the maximum number of connections. maxIdle is the maximum number of idle connections. maxWaitMillis is the maximum waiting time in milliseconds. username is the database username. password is the database password. driverClassName is the database driver class name. url is the database connection URL.

4. Save and close the context.xml file.
5. In the project, you can use the following configuration to retrieve connections from the connection pool:

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.sql.DataSource;

import java.sql.Connection;

import java.sql.SQLException;

public class YourClass {

    private static DataSource dataSource;

    static {

        try {

            Context initContext = new InitialContext();

            Context envContext = (Context) initContext.lookup("java:/comp/env");

            dataSource = (DataSource) envContext.lookup("jdbc/yourDataSourceName");

        } catch (NamingException e) {

            e.printStackTrace();

        }

    }

    public Connection getConnection() throws SQLException {

        return dataSource.getConnection();

    }

}

When needing to use a database connection in a project, call the getConnection() method to get the connection. The above are the basic configuration steps for Tomcat connection pool, which can be adjusted and optimized according to specific requirements.

bannerAds