Caching with EhCache

Caching is sometimes a very important problem for some applications with a lot of user requests. It both solves application performance issues and minimizes application-related I/O operations. In this tutorial, I introduce you to EhCache, an open-source caching that is used by many people.

First, I will create a new Maven project as an example:

with the EhCache dependency as follows:

As an example for this tutorial, I will use EhCache to store user information and we can retrieve user information from the cache using that user’s ID.

I will create a new class to store user information:

and the main class to run the application has the following initial content:

The cache manager object in EhCache is the Cache object and to get this object, the first thing you need to do is create a new CacheManager object, using the CacheManagerBuilder class as follows:

Here, I initialize the CacheManager without any further configuration. You can, while initializing CacheManager, initialize some Cache that you want. I want to be clear, so I will initialize the Cache object later.

Now you can use the createCache() method of CacheManager to create a new Cache object for yourself. This createCache() method has two overloaded methods with the first common parameter of these two methods being the name of the cache. The second parameter is related to the cache configuration.

và:

Remember, we will cache by key and value, get value by key. Each cache will have a name, so we can declare which cache we need to get information from. When initializing the cache, we will need to declare the data type of the key and value in each cache.

In my above example, I will cache with the key as ID with the data type as Long, and my value will have the data type as User as follows:

The above code uses the CacheConfigurationBuilder class to declare the configuration information of the “user” cache. We use ResourcePoolsBuilder class with the static heap() method to declare the amount of information contained in a cache.

Now we can store cache information using put() method as follows:

Once you have the information in the cache, you can also get the information in the cache as follows:

Result:

Add Comment