Introduction to JCache JSR 107

From Resin 4.0 Wiki

Revision as of 00:00, 23 January 2013 by Rick (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Resin has supported caching, session replication (another form of caching), and http proxy caching for over ten years. When you use Resin caching you are using the same platform that has the speed and scalability of custom services written in C like NginX with the usability of Java.

JCache JSR 107 is a distributed cache that has a similar interface. The Cache object in JCache looks like a java.util.ConncurrentHashMap. In addition, JCache JSR 107 defines integration with CDI (as well as Spring and Guice). You can decorate services with interceptors that apply caching to the services just by defining annotations.


Resin 4 has support for JCache, and JCache support is required for Java EE 7.

Let's look at a small example to see how easy is to get started with JCache.


package hello.world;

import javax.cache.Cache;
import javax.cache.CacheBuilder;
import javax.cache.CacheManager;
import javax.cache.Caching;
...

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
	
	Cache<String,String> cache;
	
	public Cache<String, String> cache() {
		if (cache == null) { //building a cache
			CacheManager manager = Caching.getCacheManager("cacheManagerHello");
			CacheBuilder<String,String> builder = manager.createCacheBuilder("a");
			cache = builder.build();
		}
		return cache;
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.getWriter().append("<html><head></head><body><p>");

		String helloMessage = cache().get("hello message");
		
		if (helloMessage == null) {
			helloMessage = new StringBuilder(20)
				.append("Hello World ! <br />")
				.append(System.currentTimeMillis()).toString();

			cache().put("hello message", helloMessage); // <-------------- putting results in the cache
		}

		response.getWriter().append(helloMessage);
		

		response.getWriter().append("</p></body></html>");
	}

}

Personal tools
TOOLBOX
LANGUAGES