views:

162

answers:

2

We're running a Stateless Session Bean to retrieve some data from various locations.

What's the best way to achieve caching for this SLSB ?

Using interceptors ? Using JBossCache ?

We're using JBoss 5.0.1.

A: 

A steteless session bean itself cannot hold data between invocations as the name says it is stateless. However. you can create a stateful session bean that holds your cache and pass this bean to your stateless bean method.

void someMethod(StateFulBean sfb){
  Cache cahce = sfb.getCache();
  ...

}

When using EBJ 3.1 you can also make use of the Singleton annotation and inject the cache as a singleton into your stateless session bean.

Sylar
The "state" referred to in EJB is conversation state, not object state. SLSBs can have as much state as you like, it's just state that won't survive between two different invocations of the same bean.
skaffman
I was referring to the conversation state. Maybe I did not express clearly but since I'm no native english speaker I hereby beg your pardon.
Sylar
+1  A: 

Technically, you are allowed to retain state in a stateless session bean, it's just that the state may be cleared by the container between invocations. As as result, you should not keep the cache itself in the bean, since it may just vanish.

Since you're using JBoss Appserver already, JBossCache would seem like the clear winner here. You can configure JBossCache instances using jboss service descriptors, and your EJB can then look up the cache instance from JMX/JNDI. It's all included in JBossAS already, so no additional dependencies needed.

Using JBossCache also gives you the added bonus of a cache distributed across a cluster, if that's something of interest to you.

skaffman
Is there any existing interceptor to achieve that ? (e.g. An interceptor that would use method arguments as cache key...)I would prefer not to mix business code with caching code.
jruillier
I'm not aware of such a thing off the shelf, but JBoss EJB interceptors are pretty easy to write, so you could roll your own.
skaffman