[英]Single database connection for web application
我正在開發一個簡單的CRUD應用程序,使用JDBC建立連接並執行基本的CRUD操作。 在此過程中,創建了一個DatabaseListener來在啟動時創建一個連接對象,並將其存儲在context屬性中以供重用。
下面是代碼。
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);
}
}
}
}
我正在像這樣訪問servlet中的連接
Connection jdbcConnection = (Connection) getServletContext().getAttribute("databaseSingleConnectionObject");
我不確定這是否正確。 單個數據庫連接有什么影響?
當使用這樣的單個數據庫連接時,會使應用程序變慢且變脆。
because the connection implementation is synchronized, each user has to wait until the connection is free. 因為連接實現是同步的,所以每個用戶都必須等待,直到連接空閑為止。 如果一個用戶的查詢花了一段時間才返回,則直接增加了其他並發用戶等待的時間。 如果池中有多個連接可用,那么一個用戶花費的時間不會對其他用戶造成幾乎相同的影響(除非查詢結果占用了所有JVM的內存,或者大查詢使數據庫服務器癱瘓了)。
The connection is a network connection, they tend to go down. 連接是網絡連接,它們傾向於斷開。 如果沒有創建新連接的規定,則任何類型的超時,網絡故障或數據庫不可用的時間段(例如使數據庫脫機以進行維護)都將需要重新啟動應用程序。 使用連接池將意味着您的應用程序將能夠幸免於難,並且無需外部干預即可恢復。
這將不是線程安全的,如果是的話,性能將真的很差。 考慮使用連接池,例如DBCP或C3PO
您應該讓您的應用服務器管理數據庫連接。 在其配置文件中添加一個JNDI數據源,並在需要時從您的應用程序進行查找以獲得連接(例如,當您實例化必須訪問數據庫的類時)。 您可以將數據源配置為管理連接池,以便每個用戶會話都有自己的連接。 根據您使用的AS,使用關鍵字“ JNDI”和“ datasource”運行搜索,您將獲得有關AS配置以及如何在應用程序中實現它的更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.