DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI
  • Caching Issues With the Spring Expression Language
  • A Practical Guide to Semantic Caching With Redis LangCache
  • Caching Mechanisms Using Spring Boot With Redis or AWS ElastiCache

Trending

  • Avoiding AI Debt as a Team
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization
  • One Database, Two Models: Building AI-Friendly Java Applications With MySQL JSON Duality Views

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Java-Distributed Caching in Redis

Java-Distributed Caching in Redis

Why use caches in distributed Java applications?

By 
Nikita Koksharov
·
Feb. 13, 19 · Presentation
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
106.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

When 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:  RedissonSpringCacheManagerand  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!

Cache (computing) Redis (company)

Opinions expressed by DZone contributors are their own.

Related

  • Prompt Caching: Overriding Tokenization for Faster and More Cost-Effective AI
  • Caching Issues With the Spring Expression Language
  • A Practical Guide to Semantic Caching With Redis LangCache
  • Caching Mechanisms Using Spring Boot With Redis or AWS ElastiCache

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook