質問

JDBC / MySQLの次のConnector / Jリファレンスでは、InitialContextとDataSourceのインスタンスをキャッシュすることをお勧めします。キャッシングを解決するプライベートスタティックインスタンスを作成するだけです。スレッドの安全性に関心がある必要はありません(まったく場合)。Webアプリケーション(Restlet + GlassFish / Java EE + MySQL)にこれをキャッシュするのに最適な「場所」とは何ですか??

データアクセスクラスの root である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...
*/
    }
.

役に立ちましたか?

解決 2

Following up on BalusC's link, I can confirm that we could do the same thing when using Restlet. However, as per the code in the example to get the config instance you are passing in the ServletContext as an argument. Restlet is like 'another' framework that uses Servlets as an adapter to configure itself. So it'll be tricky to pass the ServletContext as an argument from somewhere else in the code (Restlet uses it's own Context object which is conceptually similar to ServletContext)

For my case a static method returning the cached datasource seems to be 'clean enough' but there could be other design/organization approaches.

他のヒント

If you're using JAX-RS, then you can use @Context annotation.

E.g.

@Context
private ServletContext context;

@GET
@Path("whatevers")
public List<Whatever> getWhatevers() {
    DataSource dataSource = Config.getInstance(context).getDataSource();
    // ...
}

However, if the @Resource annotation is also supported on your Restlet environment, you could make use of it as good.

@Resource(mappedName="jdbc/MySQLDB")
private DataSource dataSource

This is in turn technically better to be placed in an EJB which you in turn inject by @EJB in your webservice.

@Stateless
public class WhateverDAO {

    @Resource(mappedName="jdbc/MySQLDB")
    private DataSource dataSource

    public List<Whatever> list() {
        // ...
    }

}

with

@EJB
private WhateverDAO whateverDAO;

@GET
@Path("whatevers")
public List<Whatever> getWhatevers() {
    return whateverDAO.list();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top