简体   繁体   中英

Single database connection for web application

I am developing a simple CRUD application, using JDBC to establish connection and perform basic CRUD operations. In that process, created a DatabaseListener to create a connection object at startup and storing it in the context attribute for reuse.

Below is the code.

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;

public class DatabaseInitListner implements ServletContextListener {

    private static final Logger LOG = Logger.getLogger(DatabaseInitListner.class);

    private DBUtil databaseUtil = null;

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        databaseUtil.closeConnection();
    }

    @Override
    public void contextInitialized(ServletContextEvent contextinitEvent) {

        ServletContext servletContext = contextinitEvent.getServletContext();
        String database = servletContext.getInitParameter("db_name");
        String url = servletContext.getInitParameter("db_url")
                + database;
        String username = servletContext.getInitParameter("db_user");
        String password = servletContext.getInitParameter("db_password");
        String driverName = servletContext.getInitParameter("db_driver");

        databaseUtil = new DBUtil(url, username, password,
                driverName);
        servletContext.setAttribute("databaseSingleConnectionObject",
                databaseUtil.getConnection());
    }
}

public class DBUtil {
    private Connection connection = null;
    private static final Logger LOG = Logger.getLogger(DatabaseUtil.class);
    public DatabaseUtil(String url, String username, String password,
            String driver) {
        try {
            Class.forName(driver);
            this.connection = DriverManager.getConnection(url, username,
                    password);
            LOG.debug("Connection Established... ");
        } catch (ClassNotFoundException | SQLException e) {
            LOG.error("Could not create connection... ", e);
        }
    }
    public Connection getConnection() {
        return connection;
    }
    public void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.error("Unable to close connection... ", e);
            }
        }
    }
}

I am accessing the connection in servlets like this

Connection jdbcConnection = (Connection) getServletContext().getAttribute("databaseSingleConnectionObject");

I am not sure if this is right approach. What are the effects of single database connection?

When you use a single database connection like this you make your application slow and brittle.

Slow: because the connection implementation is synchronized, each user has to wait until the connection is free. If one user's query takes a while to come back that directly increases the time any other concurrent users spend waiting. If there were multiple connections available from a pool then the time spent by one user would not impact other users nearly as greatly (unless a query's results take all the JVM's memory or a big query bogs down the database server).

Brittle: The connection is a network connection, they tend to go down. Without a provision to create new connections any kind of timeout, network hiccup, or period of database non-availability (such as taking the database offline for maintenance) is going to require an application restart. Using a connection pool will mean your application will be able to survive these episodes and recover without outside intervention.

This will not be threadsafe, and if it were, performance would be really poor. Look into using a Connection Pool, like DBCP or C3PO

You should let your application server manage database connection. Add a JNDI datasource in its configuration file and make a lookup from your application to get a connection when needed (for instance when you instantiate a class that must access your database). You may configure the datasource to manage a connection pool so that each user session will get its own. Depending on the AS you use run a search with keywords 'JNDI' and 'datasource' and you will get further details about the AS configuration and how to implement it in your application.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM