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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Caching RESTful API Requests With Heroku Data for Redis
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Simple Sophisticated Object Cache Service Using Azure Redis

Trending

  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • A Guide to Developing Large Language Models Part 1: Pretraining
  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 user avatar
Nikita Koksharov
·
Feb. 13, 19 · Presentation
Likes (16)
Comment
Save
Tweet
Share
104.5K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Caching RESTful API Requests With Heroku Data for Redis
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Simple Sophisticated Object Cache Service Using Azure Redis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!