【发布时间】:2011-02-19 00:38:49
【问题描述】:
在下面的 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...
*/
}
【问题讨论】:
-
我对 Restlet 部分一无所知,但在普通的 Servlet 环境中,您会为此使用
ServletContextListener。 Example here。如果您熟悉 Servlet,这可能会带来新的见解。 -
@BalusC:似乎可行...我会在实施后发布确认!自从我开始编写网络应用程序以来已经有一段时间了——我完全忘记了 ServletContext!非常感谢。
-
由于 InitialContexts 不是线程安全的(docs.oracle.com/javase/7/docs/api/javax/naming/…),我猜缓存必须小心。我不确定 DataSource 是否有同样的问题(似乎没有)
标签: jdbc jakarta-ee restlet-2.0 connector-j