Strongest Java Redis client

Why use caching in Java distributed applications?

Every millisecond is important in improving application speed and performance. According to a Google study, if a website fails to load successfully in 3 seconds or less, 53% of mobile phone users will leave.

Caching is one of the important technologies to accelerate distributed applications. The closer the stored information is to the CPU, the faster the access speed is. Loading data from the CPU cache is much faster than loading from RAM, much faster than loading from hard disk or network.

To store frequently accessed data, distributed applications need to maintain caches in multiple machines. Distributed caching is an important strategy to reduce latency and improve concurrency and scalability of distributed applications.

Redis is a popular open source in memory data store, which can be used as database, cache or message broker. Because data is loaded from memory rather than disk, redis is faster than many traditional database solutions.

However, it is a huge challenge for developers to make Redis distributed cache work correctly. For example, local cache invalidation, that is, replacing or deleting cache entries, must be handled with caution. Each time you update or delete information stored in the computer's local cache, you must update the cache in the memory of all computers in the distributed cache system.

The good news is that there are Redis frameworks like Redisson that can help build the distributed cache required by applications. The next section discusses three important implementations of distributed caching in Redisson: Maps, Spring Cache, and JCache.

1. Redisson distributed cache

Redisson is a Redis based framework that implements a Redis wrapper and interface in Java.

Redisson contains many common Java classes, such as distributed objects, distributed services, distributed locks and synchronizers, and distributed collections.

As will be described below, some of these interfaces support both distributed and local caching.

2. Map

Map is one of the most useful collections in Java. Redisson provides a Java Map implementation called RMap, which supports local caching.

If you want to perform multiple read operations or network round trips, use RMap that supports local caching. By storing Map data locally, RMap is 45 times faster than when local caching is not enabled. RMapCache is used for general distributed cache and RLocalCachedMap is used for local cache.

Redis engine can execute caching itself, and there is no need to execute code on the client. However, although local caching can significantly improve read speed, it needs to be maintained by developers and may require some development work. Redisson provides the RLocalCachedMap object for developers to make local caching easier to implement.

The following code shows how to initialize the RMapCache object:

RMapCache<String, SomeObject> map = redisson.getMapCache("anyMap");
map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);

The above code puts the string "key1" into RMapCache and associates it with SomeObject(). Then it specifies two parameters, TTL is set to 10 minutes and the maximum idle time is 10 seconds.

When no longer needed, the RMapCache object should be destroyed:

map.destroy();

There is no need to destroy Redisson after it is closed.

3. Spring Cache

Spring is a Java framework for building enterprise Web applications and also provides caching support.

Redisson includes the Spring caching function and provides two objects: RedissonSpringCacheManager and redissonspringlocalcachedcache manager. Redissonspring localcachedcache manager supports local caching.

The following is an example configuration of RedissonSpringLocalCachedCacheManager 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 a new "testMap" cache: ttl=24 minutes, maxIdleTime=12 minutes
        config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
        return new RedissonSpringCacheManager(redissonClient, config);
    }
}

In addition, redisson spring cache manager can be configured by reading JSON or YAML files.

Like RMaps, each RedissonSpringCacheManager instance has two important parameters: ttl (lifetime) and maxIdleTime. If these parameters are set to 0 or undefined, the data will remain in the cache indefinitely.

4. JCache

JCache is a Java caching API that allows developers to temporarily store, retrieve, update, and delete objects from the cache.

Redisson provides Redis's JCache API implementation. The following is an example of calling JCache API with default configuration in redisson:

MutableConfiguration<String, String> config = new MutableConfiguration<>();
CacheManager manager = Caching.getCachingProvider().getCacheManager();
Cache<String, String> cache = manager.createCache("namedCache", config);

In addition, JCache can be configured using a custom configuration file, Redisson Config object, or Redisson RedissonClient object. For example, the following code uses a custom Redisson configuration to call JCache:

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 JCache implementation has passed all tests of JCache TCK. You can also verify it yourself.

Let's use cache happily!

Author: JAVA ZONE Source: https://dzone.com/articles/java-distributed-caching-in-redis

Added by Julian Pedley on Fri, 07 Jan 2022 04:22:04 +0200