2. CDI and JCache
• What is CDI?
• What is JCache?
• Demo - using Hazelcast to add caching
to a Java EE application
• Other approaches
• Questions
3. What is CDI
• Contexts and Dependency Injection
• Introduced in Java EE 6 (both Web & Full Profile)
• Integrated with other specifications in Java EE (EJB, JAX-RS,
Servlets, JSF…)
• Provides the bean lifecycle management and typesafe injection
• Largely annotation-based
• Uses
– Injection (with scoping, names, qualifiers, stereotypes and alternatives)
– Producers (factory methods)
– Interceptors
– Observers
• Can be extended with portable extensions
5. JCache and Java EE
• Can be included in Java EE applications
• Add javax.cache api and implementation jars in WEB-INF/lib
• You can use JCache in the same way a Java SE application
would use it
• JSR-107 provides standard annotations for caching, but these
are not yet implemented by containers. Hopefully this will be
part of Java EE 8
• CDI can provide dependency injection and interceptors for
JCache
6. Hazelcast
• Hazelcast is a fully compliant implementation of JCache
• Very easy to add to your Java EE application
– Add com.hazelcast:hazelcast:3.5.3 and javax.cache:cache-api:1.0.0 to your POM.xml
• Add hazelcast.xml to the classpath
• Or use JCache / Hazelcast API directly
<cache name="mycache">
<key-type class-name="java.lang.Object" />
<value-type class-name="java.lang.Object" />
<statistics-enabled>true</statistics-enabled>
<management-enabled>true</management-enabled>
</cache>
final MutableConfiguration<Object, Object> config = new MutableConfiguration<Object, Object>()
.setTypes(Object.class, Object.class)
.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_HOUR))
.setStatisticsEnabled(true);
cache = mgr.createCache("mycache", config);
7. What is TomEE?
• Tomcat + Java EE = TomEE
• Pronounced “Tommy”
• Java EE 6 Web Profile certified
• Java EE 7 in progress
• Built from All-Apache Components
• What we’ve all been building ourselves
– ... for years
8.
9. TomEE Goals
• Be simple
• Avoid complexity and making users work
• Be Tomcat
• Should work with Tomcat tools and apps
• Be Certified
• Drop-in replacement for any Java EE Web
Profile server
11. Alternative Approaches?
• Use Hazelcast directly as opposed to using the JCache API
– Non-portable, but, exposes a lot more functionality in Hazelcast
– Can still use CDI Producers and create your own interceptors
@Produces
@Singleton
@Hazelcast
public HazelcastInstance createHazelcastInstance() {
final String configFile = "META-INF/hazelcast.xml";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL location = loader.getResource(configFile);
final Config config = new Config();
config.setConfigurationUrl(location);
config.setInstanceName("ExampleInstance");
return Hazelcast.newHazelcastInstance(config);
}
12. Alternative Approaches?
• Session replication filter
– http://hazelcast.com/use-cases/web-session-clustering/generic-web-
session-replication/
– Native version for Tomcat / Jetty for Enterprise users
I’m Jon Gallimore from Tomitribe, I’m a software engineer working with Apache TomEE.
In this presentation I’ll show you how you can use Jcache with CDI to easily add caching to a Java EE application.
I’ll start with a very quick introduction to CDI (which could be a session in itself) and an introduction to Jcache.
Then I’ll run through a demo showing how to add caching to an existing Java EE application running in Apache TomEE using Hazelcast as the caching provider.
Finally, we’ll wrap up looking at some alternative approaches and answering any questions.
CDI – is short for Contexts and Dependency Injection and was introduced into Java EE in version 6, in both the web and full profile.
For those of you that are unfamiliar, in Java EE 6, the functionality was split into two profiles in EE 6 – the full profile that includes everything, and the web profile which is a much cut-down version of Java EE which removes some of the older, less used APIs and keeps the APIs most commonly used in Java webapps, including EJB lite, JPA, Servlets and CDI.
Although a more recent addition, CDI is well integrated with the rest of Java EE and can be used seamlessly with EJBs, JAX-RS etc).
CDI essentially provides lifecycle management and typesafe injection of beans. Common usages of CDI are DI, producers (these are much like factory methods), interceptors (which allows you to change parameters or the method result or even avoid invoking the method altogether. Observers are a great feature of CDI, allowing events to be fired from one bean, and observed by another.
For the most part, CDI is annotation based with very little XML configuration. Additional configuration is usually provided by creating new annotations.
One of the really great things about CDI is that it can extended, and this can be achieved by extending the Extension interface. This essentially gives you hook into the container that allows you to manipulate the beans in the container. In the demo, I’ll show you a small library that implements a CDI extension that sets up the CacheManager so it can be injected. This CDI extension mechanism is portable between CDI containers, so extending CDI in this way does not restrict you to a particular application server.
CDI is quite a big topic, and if you’re new to it, and want to get into it more, have a look at the TomEE examples. There are a number of simple examples showing each CDI concept individually complete with unit tests. Alex Soto has also got some great videos on his YouTube channel.
Jcache is the standard Java caching specification. Completed last year, it was one of the longest running JSRs. Like a lot of specifications, there are a number of different implementations, and to use Jcache in your application, you need to include the jcache api JAR and the implementation jars for the specific implementation you wish to use.
There are essentially 4 key concepts in Jcache:
Caching provider – the implementation if Jcache being used. Can orchestrate multiple cache managers
Caching manager – looks after zero of more named caches
Cache – holds zero of more entries (data)
Entry – abstraction of a key-value pair
The slide shows the basic “hello world” equivalent for Jcache. We pick up the default cache provider from the classpath, get the cache manager, obtain a named cache (called “default”) and add some data.
At this point, you can probably appreciate that you can add Jcache to your existing Java EE application by adding the necessary libraries and using it in a Java SE way. However, this will require you to manage everything yourself, and will also make for a pretty terrible demo for me.
Fortunately, the Jcache specification provides a number of annotations that can be added to methods to trigger cache operations. The intention is that these will be implemented by the application servers, as opposed to each individual Jcache provider. Jcache is not part of Java EE 7, but hopefully will be in a future version of Java EE. However, if that doesn’t meet your “right-now” urges, no problem – you can use these annotations today and you should be able to switch over to the server provided annotations when they become available with minimal code changes.
Hazelcast fully implements the Jcache specification as of late last year. It provides a huge range of functionality beyond caching, including a in-memory data grid and map/reduce functionality. Hazelcast implements caching from the ground-up as opposed to just adding a wrapper on top of its existing functionality. As you’d expect, the cache data is replicated across nodes, so there is no interruption to the cache if one of the noded drops out.
Very easy to add to your application – just add the necessary jars. 3.5.3 is the latest version which I’ll be using here. Configuration can be provided within hazelcast.xml on the classpath, or configure programmatically.
Just for those of you that have not come across TomEE before…
There are a number of flavours of TomEE, each with a set of components. Note that we use JAX-RS here, but that is not part of the webprofile in EE6 (it is in 7).
Ok, enough talk, lets look at the code.
- Demo the existing app
Add the libraries (talk about the tomitribe lib)
Add hazelcast.xml
Create a producer
Add the annotation
Inject into the bean
Show the cache annotations
Cache key producer
Demonstrate with the cache
Opens up more of the Hazelcast API.
If your application stores state in a session, Hazelcast provide a session replication filter.