How to Use Redis Cache in Java

Caching is a fundamental component of any modern database solution. In caching, data that is frequently accessed is stored in memory, dramatically improving database performance by making this data faster to retrieve.

Redis is an open-source in-memory data structure store with a wide range of use cases, including NoSQL databases, caches, and message brokers. Because it is known for its fast read and write operations, Redis heavily depends on caching for these high-performance applications.

What Is Caching in Redis?

Redis-based applications can store information in a cache, fetching this information faster than if it has to be retrieved from somewhere else, e.g., fetching it from disk, computing it, or querying an external API (application programming interface). As a result, caching in Redis can significantly lower response times and lessen the database load.

Redis offers a number of data structures—including strings, hashes, lists, sets, and sorted sets—for efficient caching of different types of data. In addition, Redis includes features such as expiration times, eviction policies, and persistence options so that you can effectively manage this cached data.

Redis Cache in Java with Redisson

Redis is a powerful and widely used component in many applications. However, developers who want to use Redis should know that Redis isn't compatible with programming languages such as Java out of the box. Instead, Java developers looking to work with Redis can install a third-party Redis Java framework such as Redisson.

Redisson is a Redis Java client that makes it as simple as possible for Java developers to start using Redis databases. The Redisson library includes many familiar Java data structures, services, and components, all reworked to be compatible with Redis. For example, Redisson includes Java-based data structures such as RList, RSet, and RMap that correspond to the Redis data structures mentioned above, helping Java developers implement caching in Redis.

How to Implement Redis Caching in Java

Redisson gives developers many different options for implementing Redis caching in Java, depending on your needs. In this section, we'll go over the various ways of using Java and Redisson for your Redis cache, from the most basic to the most advanced.

Redis Hash

The Redis hash implements the hashtable or hashmap data structure in Redis. Hashtables are commonly used data structures that map unique keys to values and that are optimized for quick lookup operations.

With Redisson, Java developers can also take advantage of Redis hashes using the RMap interface, a distributed implementation of Java's Map and ConcurrentMap interfaces. Below is a simple example of how to use RMap in Redisson:

RMap map = redisson.getMap("anyMap");
SomeObject prevObject = map.put("123", new SomeObject());
SomeObject currentObject = map.putIfAbsent("323", new SomeObject());
SomeObject obj = map.remove("123");

// use fast* methods when previous value is not required
map.fastPut("a", new SomeObject());
map.fastPutIfAbsent("d", new SomeObject());
map.fastRemove("b");

Redisson includes features to improve the performance of RMap, including:

  • Local caching that significantly improves read times and lowers network latency.
  • Eviction policies to ensure that the cache always contains up-to-date information.
  • Data partitioning across multiple Redisson clusters for high scalability.

In addition, the Redisson PRO version can perform read/write operations up to 4 times faster than the base version of Redisson.

Local Caching

Local caching is a technique in which part or all of a database cache is stored closer to the application that accesses the cache, such as the client's own hard drive. While local caching can significantly improve database performance, it also needs to be handled with care to avoid duplicating data and ensure consistency between the cache and the database.

Redisson provides multiple ways of doing local caching in Redis with Java. The RLocalCachedMap interface in Redisson extends Java's built-in ConcurrentMap interface to provide support for local caching in Redis. This local cache allows Redis applications to execute read operations up to 45 times faster than normal.

The below code demonstrates how to use RLocalCachedMap for local caching in Redis with Java:

RLocalCachedMap map = redisson.getLocalCachedMap("test", LocalCachedMapOptions.defaults());

String prevObject = map.put("123", 1);
String currentObject = map.putIfAbsent("323", 2);
String obj = map.remove("123");

// use fast* methods when previous value is not required
map.fastPut("a", 1);
map.fastPutIfAbsent("d", 32);
map.fastRemove("b");

Redisson PRO users also have access to three interfaces based on third-party Java frameworks used for local caching: Spring Cache, Hibernate Cache, and JCache. Respectively, these interfaces are:

  • RedissonSpringLocalCachedCacheManager
  • RedissonLocalCachedRegionFactory
  • LocalCacheConfiguration

To learn more about these options, consult this guide to Redis local caching with Java.

Hibernate Caching

Hibernate caching makes use of the Hibernate framework for object-relational mapping (ORM), helping streamline relational database operations. The Hibernate second-level cache is an L2 cache that can be enabled in Hibernate. Data in the Hibernate L2 cache is associated with a SessionFactory object, which allows the data to persist across multiple sessions.

Redisson offers full support for Hibernate caching, including Hibernate L2 caching. The below code demonstrates how to configure Hibernate to enable L2 caching and Redisson compatibility:

< !-- 2nd level cache activation -->
< property name="hibernate.cache.use_second_level_cache" value="true" />
< property name="hibernate.cache.use_query_cache" value="true" />

< !-- Redisson YAML config (located in filesystem or classpath) -->
< property name="hibernate.cache.redisson.config" value="/redisson.yaml" />
< !-- Redisson JSON config (located in filesystem or classpath) -->
< property name="hibernate.cache.redisson.config" value="/redisson.json" />

For more information, check out the Redisson Hibernate page on GitHub.

JCache Caching

JCache is the standard caching API for Java. The CachingProvider interface in JCache allows developers to temporarily cache Java objects.

Redisson includes an implementation of the JCache API for Redis. The code below demonstrates how to use JCache with Redis by loading either a JSON or YAML configuration file:

MutableConfiguration config = new MutableConfiguration<>();

// YAML configuration
URI redissonConfigUri = getClass().getResource("redisson-jcache.yaml").toURI();

CacheManager manager = Caching.getCachingProvider().getCacheManager(redissonConfigUri, null);
Cache cache = manager.createCache("namedCache", config);

Redisson passes all of the Technology Compatibility Kit (TCK) tests for JCache, making it a fully certified implementation.

Spring Cache Caching

Spring is a lightweight, flexible application framework for the Java programming language. Since Spring 3.1 in 2012, the Spring framework has included support for caching. Specifically, caching is part of Spring Boot, a component of the Spring ecosystem for rapid application development (RAD) and microservices. Java developers need to enable Spring caching with the @EnableCaching annotation.

Redisson allows Java developers to implement Spring caching in Redis, making read operation speeds up to 45 times faster. Developers who use Java with Redis for Spring caching should be aware of two cache eviction policy parameters:

  • ttl: The ttl (time to live) parameter controls how long an object will "survive" in the cache. Once this time limit is up, the object will be deleted from the cache, no matter how often it is requested.
  • maxIdleTime: The maxIdleTime parameter controls how much time can elapse between two different cache requests for the same object. For example, if maxIdleTime is set to 10,000, then the object will be deleted once 10,000 milliseconds (10 seconds) have elapsed without a request for the object.

In Redisson, both ttl and maxIdleTime are specified using milliseconds. If these parameters are set to 0 or undefined, then objects will live in the cache indefinitely.

The example code below shows how to perform Spring caching in Redis using Redisson:

@Configuration
@ComponentScan
@EnableCaching
public class Application {
    @Bean(destroyMethod="shutdown")
    RedissonClient redisson() {
        Config config = new Config();
        config.useSingleServer()
              .setAddress("redis://127.0.0.1:6379");
        return Redisson.create(config);
   
    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map config = new HashMap<>();

        // create "testMap" spring cache with ttl = 24 minutes and maxIdleTime = 12 minutes
        config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
        return new RedissonSpringCacheManager(redissonClient, config);
    }
}

}

Tomcat Web Session Caching

Apache Tomcat is an open-source web server that implements technologies such as Java Servlet, JavaServer Pages (JSP), WebSocket, and Java Expression Language (EL). Redisson's Tomcat Session Manager allows developers to store Tomcat sessions in Redis, distributing requests across a cluster of Tomcat servers. This is particularly useful if you are expecting a lot of web traffic (e.g., if your site will be expanding), or if you just need more help to achieve high availability.

To learn more about how to perform Tomcat session management in Redis with Java and Redisson, check out our guide "Redis-Based Tomcat Session Management."

Similar articles