Out-of-process distributed caching

Extend the capabilities of your caching layer by integrating Ehcache into your Java Enterprise projects

(For more resources related to this topic, see here.)

Getting ready

Out-of-process caching is a way of distributing your caching needs in a different JVM and/or infrastructure. Ehcache provides a convenient deployable WAR file that works on most web containers/standalone servers whose mission is to provide an easy API interface to distributed cache. At the moment of writing, you can download it from http://sourceforge.net/projects/ehcache/files/ehcache-server/, or you can include it in your Maven POM and will be delivered as a WAR file.

The cache server requires no special configuration on the Tomcat container. However, if you are running GlassFish, Jetty, WebLogic, or any other application server (or servlet container), there are minimal configuration changes to do. Please refer to the Ehcache cache server documentation for details on these.

While using the RESTful interface, it is important to note that you have three ways to set the MIME type for exchanging data back and forth to the cache server, namely Text/XML, application/JSON, and application/x-java-serialized-object.

You can use any programming language to invoke the web service interface and cache your objects (except for application/x-java-serialized-object for obvious reasons).

Refer to the recipe8 project directory within the source code bundle for a fully working sample of this recipe content and further information related to this topic.

How to do it...

  1. Add Ehcache and Ehcache cache server dependencies to your POM.xml file.

    <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-server</artifactId> <version>1.0.0</version> <type>war</type> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.6.0</version> <type>pom</type> </dependency>

  2. Edit ehcache.xml in the cache server to hold your cache setup (the cache name is very important).

    You can find this file here: ${CACHE_SERVER}/WEB-INF/classes/ehcache.xml.

    <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <!-- Set cache eternal (of course not to do in production) --> <cache name="remoteCache" maxElementsInMemory="10000" eternal="true" diskPersistent="true" overflowToDisk="true"/> ...

  3. Disable the SOAP interface in the cache server web.xml (since we are going to use RESTful) file:

    You can find this file here: ${CACHE_SERVER}/WEB-INF/web.xml.

    <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> ... <!-- SOAP Servlet Comment out (or remove) to disable SOAP Web Services <servlet> <servlet-name>EhcacheWebServiceEndpoint</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet
    </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>EhcacheWebServiceEndpoint</servlet-name> <url-pattern>/soap/EhcacheWebServiceEndpoint</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</session-timeout> </session-config> <listener> <listener-class> com.sun.xml.ws.transport.http.servlet.WSServletContextListener </listener-class> </listener> --> ...

  4. Make your objects-to-be-cached serializable:

    import java.io.Serializable; public final class Item implements Serializable {

  5. Invoke the RESTful (or SOAP) interface to save/retrieve/delete cached objects:

    ... public void saveItemInCache(String key, Serializable item) { //sample URL: http://localhost:8080/ehcache/rest/cacheName/{id} //here cacheName is the cache name you
    set up in the cache-server ehcache.xml String url = CACHE_SERVER_URL + "cacheName" + "/" + key; //initialize Apache HTTP Client client = new DefaultHttpClient(); //create Cache Element to be sent Element element = new Element(key, item); //serialize object to be sent to EhCache Server byte[] itemToByteArray = SerializationUtils.serialize(element); //create PUT request HttpPut putRequest = new HttpPut(url); //set header to read java-serialized-object mime type putRequest.setHeader
    ("Content-Type", "application/x-java-serialized-object"); ...

How it works...

The Ehcache cache server utility is a versatile tool that lets us distribute cache engines in a very flexible way. It provides a very simple API exposure via RESTful or SOAP-based web services.

We start by editing the ehcache.xml configuration file within the cache server application by adding a cache that we would like to use for our cached objects:

... <!-- Set cache eternal (of course not to do in production) --> <cache name="remoteCache" maxElementsInMemory="10000" eternal="true" diskPersistent="true" overflowToDisk="true"/> ...

The cache name defined here is very important because this will be the endpoint of our RESTful URL pattern that the cache server will identify and use.

Then, we need to edit the web.xml file within the cache server application (located in {CACHE-SERVER}/WEB-INF/) in order to comment out (or completely remove) service definitions that we are not going to use (that is, SOAP if you are using RESTful or vice versa).

<!-- SOAP Servlet Comment out to disable SOAP Web Services <servlet> <servlet-name>EhcacheWebServiceEndpoint</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class> <load-on-startup>1</load-on-startup> </servlet> ...

In order to cache an object (specially a Java object), we need to make it serializable simply by implementing the Serializable interface (this is not a requirement for MIME types different from the application/x-java-serialized-object).

import java.io.Serializable; public final class Item implements Serializable {

Finally, we invoke the RESTful endpoint from our code to store/retrieve/delete the object from/to the cache layer.

//sample URL: http://localhost:8080/ehcache/rest/cacheName/{id} //here cacheName is the cache name
you set up in the cache-server ehcache.xml String url = CACHE_SERVER_URL + "cacheName" + "/" + key; //set header to read json mime type putRequest.setHeader("Content-Type", "application/json");

It is important to note here that the cacheName URL parameter represents the cache name you defined in the ehcache.xml configuration file in the cache server application. You have defined your cache name as follows:

 <!-- Set cache eternal (of course not to do in production) -->
 <cache name="remoteCache"
        maxElementsInMemory="10000"
 ...

Now, your URL would be something like this:

//sample URL: http://localhost:8080/ehcache/rest/remoteCache/{id}

Here, id is just the key value you assign to the cached object.

Finally, you just use any http/SOAP client library (or Java default Net API classes) to invoke the web service. In the case of RESTful services, you need to be aware that the HTTP method sent determines whether you are storing, updating, retrieving, or deleting a cached item. They are as follows:

  • GET /{cache}/{element}: This retrieves an object by its key from the O-O-P cache layer.
  • PUT /{cache}/{element}: This stores an item in the O-O-P cache layer.
  • DELETE /{cache}/{element}: This deletes an item from the O-O-P cache layer.
  • HEAD /{cache}/{element}: This retrieves metadata (cache configuration values) from the O-O-P cache layer.
  • OPTIONS /{cache}/{element}: This returns the WADL describing operations.

For changing the context you can edit the file ${CACHE_SERVER}/META-INF/context.xml and place your desired context name.

As for security, look for the file ${CACHE_SERVER}/WEB-INF/server_security_config.xml_rename_to_activate and open it to read the instructions.

Summary

This article provided details on implementing distributed caching using the Ehcache server, and also explained in brief what out-of-process caching is.

Resources for Article :


Further resources on this subject:


Books to Consider

Apache Flume: Distributed Log Collection for Hadoop - Second Edition
$ 22.99
comments powered by Disqus