在以下针对 JDBC/MySQL 的 Connector/J 引用中,建议我们缓存 InitialContext 和 Datasource 的实例。仅将其设为私有(private)静态实例就可以解决缓存问题吗?难道人们不应该关心线程安全(如果有的话)吗?对于网络应用程序(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...
*/
}
最佳答案
如果您使用 JAX-RS,则可以使用 @Context
注释。
例如
@Context
private ServletContext context;
@GET
@Path("whatevers")
public List<Whatever> getWhatevers() {
DataSource dataSource = Config.getInstance(context).getDataSource();
// ...
}
但是,如果 @Resource
您的 ReSTLet 环境也支持注释,您也可以充分利用它。
@Resource(mappedName="jdbc/MySQLDB")
private DataSource dataSource
从技术上来说,最好将其放置在 EJB 中,然后通过 @EJB
将其注入(inject)到 Web 服务中。
@Stateless
public class WhateverDAO {
@Resource(mappedName="jdbc/MySQLDB")
private DataSource dataSource
public List<Whatever> list() {
// ...
}
}
与
@EJB
private WhateverDAO whateverDAO;
@GET
@Path("whatevers")
public List<Whatever> getWhatevers() {
return whateverDAO.list();
}
关于jdbc - 在 Java EE Web 应用程序中缓存 InitialContext 和 DataSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5048041/