Кэширование INANINATIONCONTEXT и DataSource в веб-приложении Java EE

StackOverflow https://stackoverflow.com/questions/5048041

Вопрос

В следующем соединении / J ссылки на JDBC / MySQL предлагает мы кэшируем экземпляры INALICCONTEXT и DataSource.Просто сделает его частным статическим экземпляром, решающим кэширование?Не следует беспокоиться о безопасности потоков (если вообще)?Какое лучшее «место» кэширует это для веб-приложения (Restlet + Glassfish / Java EE + MySQL) ??

Есть класс Genericdao, который является root CORT классов доступа к данным, так сказать.Так что только статические экземпляры на самом деле решают проблему?Это заставило бы некоторые из методов быть статическим, что мы не хотим.Предложения ??

Спасибо!

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