Out-of-process distributed caching

Exclusive offer: get 50% off this eBook here
Instant Effective Caching with Ehcache [Instant]

Instant Effective Caching with Ehcache [Instant] — Save 50%

Extend the capabilities of your caching layer by integrating Ehcache into your Java Enterprise projects with this book and ebook

$14.99    $7.50
by Daniel Wind | September 2013 | Open Source Web Development

In this article by Daniel Wind, author of the book Instant Effective Caching with Ehcache, talks about the steps to implement distributed caching using the Ehcache server RESTful module.

In this article, we will cover the following topics:

  • What out-of-process distributed caching is and why it is useful
  • Setting up a RESTful cache server using Ehcache
  • We will examine how to set up out-of-process distributed caching with the Ehcache cache server. This utility is provided by the Terracotta folks to ease the integration process with external systems via web services, such as SOAP and RESTful.

(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:


Instant Effective Caching with Ehcache [Instant] Extend the capabilities of your caching layer by integrating Ehcache into your Java Enterprise projects with this book and ebook
Published: August 2013
eBook Price: $14.99
See more
Select your format and quantity:

About the Author :


Daniel Wind

Daniel Wind is a Software Architect from Costa Rica who is passionate about coding and implementing scientific paradigms to achieve innovative solutions. He has worked for companies helping them by providing architecture consultancy as well as software engineering, especially in the mobile space.

Daniel started as a physics geek who got into computer science at the very moment he saw his first C-based simulation program in action. He fell in love with it and became addicted. He then moved to business-oriented software where he applied actuarial mathematics and software engineering to provide data forecast models, neural networks, and system statistics. He is an advocate of the Java technology as the industry's "new Cobol", in the sense that Java Enterprise and the de-facto solutions available solve almost all business problems.

Daniel's spare time interests range from business software needs to 3D mobile games. The latter one is an interesting topic he's up to by using the Android SDK and Blackberry NDK. When he's not coding or writing, he loves traveling with his family, listening to Coldplay, or watching his longtime hero Bear Grylls.

Books From Packt


Spring 2.5 Aspect Oriented Programming
Spring 2.5 Aspect Oriented Programming

Oracle Coherence 3.5
Oracle Coherence 3.5

Citrix Access Gateway VPX 5.04 Essentials
Citrix Access Gateway VPX 5.04 Essentials

 Microsoft Windows Azure Development Cookbook
Microsoft Windows Azure Development Cookbook

Infinispan Data Grid Platform
Infinispan Data Grid Platform

Microsoft Windows Identity Foundation Cookbook
Microsoft Windows Identity Foundation Cookbook

Easy Web Development with WaveMaker
Easy Web Development with WaveMaker

Twitter Bootstrap Web Development How-To [Instant]
Twitter Bootstrap Web Development How-To [Instant]


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software