Java-Distributed Caching in Redis
Why use caches in distributed Java applications?
Join the DZone community and get the full member experience.
Join For FreeWhen it comes to improving your application's speed and performance, every millisecond counts. According to a Google study, for example, 53 percent of mobile users will leave a website if it doesn't load in 3 seconds or less.
Caching is one of the most important techniques for making your distributed applications faster. The closer that you can store information to the computer's CPU, the more quickly it can be accessed. Loading data from the CPU cache is much faster than loading it from RAM, which is also significantly faster than loading it from a hard disk or over a network.
In order to store frequently-accessed data, distributed applications maintain caches on multiple machines. Distributed caching is often an essential strategy for decreasing a distributed application's latency and improving its concurrency and scalability.
Redis is a popular, open-source, in-memory data structure store that can be used as a database, cache, or message broker. Because it loads data from memory instead of from disk, Redis is faster than many traditional database solutions.
However, getting distributed caching to work correctly in Redis can be a challenge for developers. For example, local cache invalidation, which is the process of replacing or removing cache entries, must be handled with care. Every time that you update or delete information stored in a local cache on one machine, you must update the in-memory caches on all machines that are part of the distributed cache.
The good news is that there are Redis frameworks, such as Redisson, that can help you build the distributed cache you need for your application. In the next section, we'll discuss three significant implementations of distributed caching in Redisson: Maps, Spring Cache, and JCache.
Distributed Caching in Redisson
Redisson is a Redis-based framework that provides a wrapper and interface for working with Redis in Java. Redisson includes implementations of many familiar Java classes, including distributed objects, distributed services, distributed locks and synchronizers, and distributed collections. As we will see, several of these interfaces have support for caching and local caching.
Map
Maps are one of the most useful and versatile collections in Java. Redisson provides an implementation of Java Map (called RMap), which is available with support for local caching.
You should use an RMap with local caching if you plan to execute many read operations and/or network roundtrips. By storing the Map data locally, your read operations will be up to 45 times faster than an RMap without local caching. The RMapCache object is used for general-purpose, distributed caches, and the RLocalCachedMap object is used for local caching.
The Redis engine is capable of performing caching itself, without the need for any code on the client side. However, local caches that significantly boost the speed of reading operations will need to be maintained by developers and may take some time to implement. Redisson provides the RLocalCachedMap
object as a benefit to developers so that it is easier to implement local caches.
Below is an instantiation of the RMapCache
object:
RMapCache<String, SomeObject> map = redisson.getMapCache("anyMap");
map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);
The code above places the String "key1" into the RMapCache
and associates it with aSomeObject()
. It then specifies two parameters: a time to live (TTL) of 10 minutes and a maximum idle time of 10 seconds.
The RMapCache
object should be destroyed when it is no longer needed:
map.destroy();
However, this is not necessary if Redisson is shut down.
Spring Cache
Spring is a Java framework for building enterprise web applications, which include support for caching.
Redisson includes an implementation of the cache functionality in Spring with two objects: RedissonSpringCacheManager
and RedissonSpringLocalCachedCacheManager
. As the name suggests, RedissonSpringLocalCachedCacheManager
includes support for local caching.
Below is an example configuration of a RedissonSpringCacheManager
object:
@Configuration
@ComponentScan
@EnableCaching
public static class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException {
Config config = new Config();
config.useClusterServers()
.addNodeAddress("127.0.0.1:7004", "127.0.0.1:7001");
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = new HashMap<String, CacheConfig>();
// create "testMap" 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);
}
}
You can also configure the RedissonSpringCacheManager
by reading from a JSON or YAML file.
Like RMaps, each instance of RedissonSpringCacheManager
has two important parameters: ttl
(time to live) and maxIdleTime
. If these parameters are set to 0 or not defined, then the data will remain in the cache indefinitely.
JCache
JCache is a caching API for Java that allows developers to temporarily store, retrieve, update, and delete objects from a cache.
Redisson includes an implementation of the JCache API for Redis. Below is an example of how to use the JCache API in Redisson using the default configuration file:
MutableConfiguration<String, String> config = new MutableConfiguration<>();
CacheManager manager = Caching.getCachingProvider().getCacheManager();
Cache<String, String> cache = manager.createCache("namedCache", config);
You can also configure JCache using a file with a custom location, with Redisson's Config
object or with Redisson's RedissonClient
object. For example, the code below configures JCache using a custom Redisson configuration:
MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
Config redissonCfg = ...
Configuration<String, String> config = RedissonConfiguration.fromConfig(redissonCfg, jcacheConfig);
CacheManager manager = Caching.getCachingProvider().getCacheManager();
Cache<String, String> cache = manager.createCache("namedCache", config);
Redisson's implementation of JCache passes all tests in the JCache Technology Compatibility Kit (TCK) test suite. You can confirm this by running the tests yourself.
Happy caching!
Opinions expressed by DZone contributors are their own.
Comments