2

在下面的 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...
*/
    }
4

2 回答 2

4

如果您使用的是 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您的 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();
}
于 2011-03-31T20:25:15.327 回答
2

跟进 BalusC 的链接,我可以确认我们可以在使用 Restlet 时做同样的事情。但是,根据示例中的代码来获取您将 ServletContext 作为参数传递的配置实例。Restlet 就像“另一个”框架,它使用 Servlet 作为适配器来配置自身。因此,将 ServletContext 作为参数从代码中的其他位置传递会很棘手(Restlet 使用它自己的Context对象,在概念上类似于 ServletContext)

就我而言,返回缓存数据源的静态方法似乎“足够干净”,但可能还有其他设计/组织方法。

于 2011-03-31T19:57:28.973 回答