在下面的 JDBC/MySQL 连接器/J 参考中,它建议我们缓存 InitialContext 和 Datasource 的实例。将其设为私有静态实例会解决缓存问题吗?不应该关心线程安全(如果有的话)吗?为网络应用程序(Restlet + glassfish/Java EE + mysql)缓存它的最佳“位置”是什么?
可以说,有一个 GenericDAO 类是数据访问类的根。那么只有静态实例真的能解决问题吗?它会迫使某些方法成为我们不想要的静态方法。建议??
谢谢!
public void doSomething() throws Exception {
/*
* Create a JNDI Initial context to be able to
* lookup the DataSource
**
In production-level code, this should be cached as
* an instance or static variable, as it can
* be quite expensive to create a JNDI context.
**
Note: This code only works when you are using servlets
* or EJBs in a Java EE application server. If you are
* using connection pooling in standalone Java code, you
* will have to create/configure datasources using whatever
* mechanisms your particular connection pooling library
* provides.
*/
InitialContext ctx = new InitialContext();
/*
* Lookup the DataSource, which will be backed by a pool
* that the application server provides. DataSource instances
* are also a good candidate for caching as an instance
* variable, as JNDI lookups can be expensive as well.
*/
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/MySQLDB");
/*
*Remaining code here...
*/
}