Caching using Ehcache Java Library

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Ehcache from Terracotta is one of Java's most widely used Cache. It is concurrent and highly scalable. It has small footprint with SL4J as the only dependencies. It supports multiple strategies like Expiration policies, Eviction policies. It supports three storage tiers, heap, off-heap, disk storage. There are very few caching products supports multiple tier storage. If you want to scale, you cannot store all items in heap there should be support for off-heap and disk storage. Ehcache is licensed under Apache 2.0. In this article, we can see about basic usage of Ehcache.

Maven dependency

 <dependency>
      <groupId>org.Ehcache</groupId>
      <artifactId>Ehcache</artifactId>
      <version>3.7.0</version>
</dependency>

<dependency>
     <groupId>javax.cache</groupId>
     <artifactId>cache-api</artifactId>
     <version>1.1.0</version>
</dependency>

Let's create and initialize two cache instance. Before creating cache, we need to create Cache Manager instance which in-turn manages the cache.

 Create Cache Manager instance and initialize it.

 
     CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                                                            .build();

     cacheManager.init();

Using Cache Manager, create a cache instance which takes String as Key and User object as value. Using this cache we can store user objects for token or session. If you are building Rest application and authenticating using JWT token then you may need a cache which stores some information with respect to token. Below statement will create a cache with 100 entries in heap and the entry will stay for an hour beyond that it will be evicted. If user defined objects has to be cached then object should be serializable.

     Cache<String, User>sessionCache = cacheManager.createCache(SESSION_CACHE, 
                           CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class,
                                         User.class, ResourcePoolsBuilder.heap(100))
                           .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(1))));

 

Below statement creates a cache with String type as key and value. The cache can hold 10 MB of data in the heap and beyond that it will maintain 50 MB in off-heap. So total 60 MB of memory will be available.


     Cache<String, String>dbCache = cacheManager.createCache(DB_CACHE,
                           CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
                           ResourcePoolsBuilder.newResourcePoolsBuilder()
                                       .heap(10, MemoryUnit.MB)
                                       .offheap(50, MemoryUnit.MB)
                                       .build()));

Resource Pool builder decides how much resources to be used. First statement allocates 100 entries in heap, second one allocates 10 MB in heap, third statement allocates 10 MB in off-heap and fourth one allocates 10 MB in disk. If the cache entries are added beyond its total allocated resource pool then the older entry will be evicted.

 1. ResourcePoolsBuilder.heap(100)
 2. ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, MemoryUnit.MB)
 3. ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(10, MemoryUnit.MB)
 4. ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.MB)

 

Off Heap and Disk store

There are very few cache libraries provide off-heap and disk store. The off-heap is nothing but direct memory or memory mapped files. An application does various tasks, caching is required to speed up the process but it should not take whole a lot memory. It is good to use few resource in heap and off load remaining. Storing it in disk provides persistence. Caching is always temporary but if you want to persist after JVM restart then use disk store.

If you want to use disk then while creating Cache Manager, provide path to persist data.

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder() 
                         .with(CacheManagerBuilder.persistence("<File-System-Path>"))
                         .build();

 

Now we created cache, let's use it to store values.

   Cache<String, User>sessionCache = cacheManager.getCache(SESSION_CACHE, String.class, User.class);
   sessionCache.put(sessionId, userObj);

If you want to retrieve,

   Cache<String, User>sessionCache = cacheManager.getCache(SESSION_CACHE, String.class, User.class);
   User userObj = sessionCache.get(sessionId);

 

Now let's take a look in to the complete source

public class User implements Serializable {

   private String name;
   private String role;
   private int userId;

   public User(int userId, String name, String role) {
        this.userId = userId;
        this.name = name;
        this.role = role;
  }

   public String getName() {
        return name;
   }
   public void setName(String name) {
        this.name = name;
   }
   public String getRole() {
       return role;
   }
   public void setRole(String role) {
      this.role = role;
   }
   public int getUserId() {
     return userId;
  }
   public void setUserId(int userId) {
     this.userId = userId;
   }
 }

 

import java.time.Duration;
import org.Ehcache.Cache;
import org.Ehcache.CacheManager;
import org.Ehcache.config.builders.CacheConfigurationBuilder;
import org.Ehcache.config.builders.CacheManagerBuilder;
import org.Ehcache.config.builders.ExpiryPolicyBuilder;
import org.Ehcache.config.builders.ResourcePoolsBuilder;
import org.Ehcache.config.units.MemoryUnit;

public class CacheService {

  static CacheManager cacheManager;
  static final String SESSION_CACHE = "session-cache";
  static final String DB_CACHE = "db-cache";

  public static void initialize() {

       cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                                                               .build();

       cacheManager.init();

       Cache<String, User>sessionCache = cacheManager.createCache(SESSION_CACHE,
                       CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, User.class,
                                 ResourcePoolsBuilder.heap(100))
                                 .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(1))));

       Cache<String, String>dbCache = cacheManager.createCache(DB_CACHE,
       CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
                                     ResourcePoolsBuilder.newResourcePoolsBuilder()
                                                                   .heap(10, MemoryUnit.MB)
                                                                   .offheap(10, MemoryUnit.MB)
                                                                   .build()));
  }

  public static void initializeWithPersistance() {

       cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                                         .with(CacheManagerBuilder.persistence("<File-System-Path>"))
                                         .build();

       cacheManager.init();

      Cache<String, User>sessionCache = cacheManager.createCache(SESSION_CACHE,
                        CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, User.class,
                         ResourcePoolsBuilder.heap(100).offheap(2, MemoryUnit.MB).disk(10, MemoryUnit.MB)));

      Cache<String, String>dbCache = cacheManager.createCache(DB_CACHE,
                        CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
                        ResourcePoolsBuilder.heap(10).offheap(2, MemoryUnit.MB)));
  }

  public static void close() {
       cacheManager.close();
  }

  public static void saveUserSession(String sessionId, User userObj) {
       Cache<String, User>sessionCache = cacheManager.getCache(SESSION_CACHE, String.class, User.class);
       sessionCache.put(sessionId, userObj);
  }

   public static User getUserSession(String sessionId) {
         Cache<String, User>sessionCache = cacheManager.getCache(SESSION_CACHE, String.class, User.class);
         return sessionCache.get(sessionId);
  }

   public static void saveDbResults(String query, String resultsJson) {
         Cache<String, String>dbCache = cacheManager.getCache(DB_CACHE, String.class, String.class);
         dbCache.put(query, resultsJson);
   }

   public static String getDbResults(String query) {
         Cache<String, String>dbCache = cacheManager.getCache(DB_CACHE, String.class, String.class);
         return dbCache.get(query);
   }
}

Reference:

http://www.Ehcache.org/

http://www.Ehcache.org/apidocs/3.7.0/index.html

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

We publish blog post about open source products. If you are interested in sharing knowledge about open source products, please visit write for us

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More


An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More


PySpark: Installation, RDDs, MLib, Broadcast and Accumulator

  • pyspark spark python rdd big-data

We knew that Apace Spark- the most famous parallel computing model or processing the massive data set is written in Scala programming language. The Apace foundation offered a tool to support the Python in Spark which was named PySpark. The PySpark allows us to use RDDs in Python programming language through a library called Py4j. This article provides basic introduction about PySpark, RDD, MLib, Broadcase and Accumulator.

Read More


An introduction to web cache proxy server - nuster

  • web-cache proxy-server load-balancer

Nuster is a simple yet powerful web caching proxy server based on HAProxy. It is 100% compatible with HAProxy, and takes full advantage of the ACL functionality of HAProxy to provide fine-grained caching policy based on the content of request, response or server status. This article gives an overview of nuster - web cache proxy server, its installation and few examples of how to use it.

Read More


How hashmap works in Java. My style of learning.

  • java hashmap opensource-learning

This is the most frequently asked questions in the interview. Googling will throw many links related to this topic. How to learn the implementation of hash map? My style of learning using open source learning technique.

Read More



Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More


Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More


Thymeleaf - Text display, Iteration and Conditionals

  • thymeleaf template-engine web-programming java

Thymeleaf is a server-side Java template engine for both web and standalone environments. It is a better alternative to JavaServer Pages (JSP). Spring MVC and Thymeleaf compliment each other if chosen for web application development. In this article, we will discuss how to use Thymeleaf.

Read More


Should web application store images in Database or File system?

  • database image-store filesystem

Web developers most frequent question, Should user images be stored in database or file system? Which is the best way. Both has some pros and cons.

Read More


Holistic usage guide for OpenSSL

  • openssl security certificate tools

OpenSSL is a general purpose cryptographty toolkit that provides an open source implementation of Transport Layer Security(TLS) and Secure Socket Layer(SSL) protocols. It is written in C,assembly and Perl language but wrappers are available in all languages. This article explains about OpenSSL commands.

Read More


Ngnix - High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy

  • load-balancer proxy-server web-server

Nginx is a High Performance Web Server, Proxy Server, Content Cache and Reverse Proxy server. It can also be used as mail proxy server and a generic TCP/UDP proxy server. Nginx claims to be more efficient and faster in the Web space compared to the other web servers. This can be evident with the architecture which is based on asynchronous event-driven approach. The event driven architecture enables to scale to hundreds / thousands of concurrent connections.

Read More


Advanced Programming Guide in Redis using Jedis

  • redis jedis advanced-guide cluster pipline publish-subscribe

Redis is an in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This blog covers the advanced concepts like cluster, publish and subscribe, pipeling concepts of Redis using Jedis Java library.

Read More


Introduction to Apache Cassandra

  • cassandra database nosql

Apache Cassandra was designed by Facebook and was open-sourced in July 2008. It is regarded as perfect choice when the users demand scalability and high availability without any impact towards performance. Apache Cassandra is highly scalable, high-performance distributed database designed to handle large voluminous amounts of data across many commodity servers with no failure.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


LetsEncrypt certificate using ZeroSSL tools

  • ssl-certificate certificate security

Let’s Encrypt is a free, automated, and open Certificate Authority. It uses ACME protocol to validate your domain. If you have complete control over your domain, you can get a certificate for free. In order to provide secure access to your public network like HTTPS, LDAPS etc you need a certificate from a Certificate Authority. The cost of the certificate range from 10$ to 100$. If you want a wildcard certificate then it may cost more. The certificate is valid for one year and you need to pay and renew every year. Let's Encrypt comes for the rescue. You can create and renew certificate for few.

Read More


How Bitcoin works? A simple introduction.

Bitcoin is an open source digital currency which could be transferred in a P2P payment network. It is decentralized and it is not controlled by any central authority or banks. It is transferred from person to person and no authority will be aware of your transaction. Its quite different from PayPal or Banks.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More


Univention Corporate Server - An open source identity management system

  • ucs identity-management-system

Univention Corporate Server is an open source identity management system, an IT infrastructure and device management solution and an extensible platform with a store-like App Center that includes tested third party applications and further UCS components: This is what Univention combines in their main product Univention Corporate Server, a Debian GNU/Linux based enterprise distribution. This article provides you the overview of Univention Corporate Server, its feature and installation.

Read More


Identicon - Get unique avatar for your website users

  • identicon avatar icon gravatar

Users login in to the Websites, Blogs, Forum and adding their content, comments, asking or answering the questions etc. If user has added his photo then it will get displayed besides his content but not everyone provides his photo image to the sites. Most of the sites used to display a common avatar image for those who have not provided their image. When we read the content, it may be odd to see the same image representation for all users. Identicon comes for the rescue.

Read More