Tutorial

Spring Boot Redis Cache

Published on August 3, 2022
Default avatar

By Shubham

Spring Boot Redis Cache

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Spring Boot Redis Cache

spring boot redis cache In this post, we will setup up a sample Spring boot application and integrate it with Redis Cache. While Redis is an Open source in-memory data structure store, used as a database, cache and message broker, this lesson will demonstrate only the caching integration. We will make use of Spring Initializr tool for quickly setting up the project.

Spring Boot Redis Project Setup

We will make use of Spring Initializr tool for quickly setting up the project. We will use 3 dependencies as shown below: spring boot redis cache example Download the project and unzip it. We have used H2 database dependency as we will be using an embedded database which loses all data once the application has been stopped.

Spring Boot Redis Cache Maven Dependencies

Though we already completed the setup with the tool, if you want to set it up manually, we use Maven build system for this project and here are the dependencies we used:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.9.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
</properties>
<dependencies>
  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
  </dependency>

  <!-- for JPA support -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

  <!-- for embedded database support -->
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>

</dependencies>

<build>
  <plugins>
     <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
     </plugin>
  </plugins>
</build>

Make sure to use stable version for Spring Boot from the maven central.

Defining the Model

To save an object into the Redis database, we define a Person model object with basic fields:

package com.journaldev.rediscachedemo;

import javax.persistence.*;
import java.io.Serializable;

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 7156526077883281623L;

    @Id
    @SequenceGenerator(name = "SEQ_GEN", sequenceName = "SEQ_USER", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
    private Long id;
    private String name;
    private long followers;

    public User() {
    }

    public User(String name, long followers) {
        this.name = name;
        this.followers = followers;
    }

    //standard getters and setters

    @Override
    public String toString() {
        return String.format("User{id=%d, name='%s', followers=%d}", id, name, followers);
    }
}

It is a standard POJO with getters and setters.

Configuring Redis Cache

With Spring Boot and the required dependency already in work with Maven, we can configure local Redis instance with only three lines in our application.properties file as:

# Redis Config
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379

Also, use the @EnableCaching annotation on Spring Boot main class:

package com.journaldev.rediscachedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Application implements CommandLineRunner {

  private final Logger LOG = LoggerFactory.getLogger(getClass());
  private final UserRepository userRepository;

  @Autowired
  public Application(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override
  public void run(String... strings) {
    //Populating embedded database here
    LOG.info("Saving users. Current user count is {}.", userRepository.count());
    User shubham = new User("Shubham", 2000);
    User pankaj = new User("Pankaj", 29000);
    User lewis = new User("Lewis", 550);

    userRepository.save(shubham);
    userRepository.save(pankaj);
    userRepository.save(lewis);
    LOG.info("Done saving users. Data: {}.", userRepository.findAll());
  }
}

We have added a CommandLineRunner as we want to populate some sample data in the embedded H2 database.

Defining the Repository

Before we show how Redis works, we will just define a Repository for JPA related functionality:

package com.journaldev.rediscachedemo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository { }

It has no method calls as of now as we don’t need any.

Defining the Controller

Controllers are the place where Redis cache is called for action. Actually, this is the best place to do so because as a cache is directly associated with it, the request won’t even have to enter the service code to wait for cached results. Here is the controller skeleton:

package com.journaldev.rediscachedemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

  private final Logger LOG = LoggerFactory.getLogger(getClass());

  private final UserRepository userRepository;

  @Autowired
  public UserController(UserRepository userRepository) {
    this.userRepository = userRepository;
  }
   ...
}

Now, to put something into the cache, we use @Cacheable annotation:

@Cacheable(value = "users", key = "#userId", unless = "#result.followers < 12000")
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable String userId) {
  LOG.info("Getting user with ID {}.", userId);
  return userRepository.findOne(Long.valueOf(userId));
}

In the above mapping, getUser method will put a person into a cache named as ‘users’, identifies that person by the key as ‘userId’ and will only store a user with followers greater than 12000. This makes sure that cache is populated with users who are very popular and are often queried for. Also, we have intentionally added a log statement in the API call. Let’s make some API calls form Postman at this moment. These are the calls we made:

localhost:8090/1
localhost:8090/1
localhost:8090/2
localhost:8090/2

If we notice the logs, these will be it:

... : Getting user with ID 1.
... : Getting user with ID 1.
... : Getting user with ID 2.

Notice something? We made four API calls but only three log statements were present. This is because the User with ID 2 is having 29000 followers and so, it’s data was cached. This means that when an API call was made for it, the data was returned from the cache and no DB call was made for this!

Updating Cache

Cache values should also update whenever their actual objects value are updated. This can be done using @CachePut annotation:

@CachePut(value = "users", key = "#user.id")
@PutMapping("/update")
public User updatePersonByID(@RequestBody User user) {
  userRepository.save(user);
  return user;
}

With this, a person is again identified by his ID and is updated with the results.

Clearing Cache

If some data is to be deleted from actual Database, there won’t be a point to keep it in cache anymore. We can clear cache data using @CacheEvict annotation:

@CacheEvict(value = "users", allEntries=true)
@DeleteMapping("/{id}")
public void deleteUserByID(@PathVariable Long id) {
  LOG.info("deleting person with id {}", id);
  userRepository.delete(id);
}

In the last mapping, we just evicted cache entries and did nothing else.

Running Spring Boot Redis Cache Application

We can run this app simply by using a single command:

mvn spring-boot:run

Redis Cache Limits

Although Redis is very fast, it still has no limits on storing any amount of data on a 64-bit system. It can only store 3GB of data on a 32-bit system. More available memory can result into a more hit ratio but this will tend to cease once too much memory is occupied by Redis. When cache size reaches the memory limit, old data is removed to make place for new one.

Summary

In this lesson, we looked at what power Redis Cache provides us with fast data interaction and how we can integrate it with Spring Boot with minimal and yet powerful configuration. Feel free to leave comments below.

Download Spring Boot Redis Cache Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Shubham

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 19, 2021

Hello! I believe that we must also have an instance of Redis running in order for this code to work. I run it on docker, with the following command (to create the instance, then everytime I want to enable it, I go to Docker desktop to do it, for example): docker run -it --name redis-cache-name -p 6379:6379 redis:5.0.3

- Guilherme Amoroso Romão

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 28, 2021

    Not working with PUT request

    - Nitin

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 9, 2020

      not work The following candidates were found but could not be injected: - Bean method ‘redisConnectionFactory’ in ‘RedisConfig’ not loaded because @ConditionalOnProperty (aps.cache.type=redis) found different value in property ‘aps.cache.type’ - Bean method ‘redisConnectionFactory’ in ‘JedisConnectionConfiguration’ not loaded because @ConditionalOnClass did not find required classes ‘org.apache.commons.pool2.impl.GenericObjectPool’, ‘redis.clients.jedis.Jedis’ - Bean method ‘redisConnectionFactory’ in ‘LettuceConnectionConfiguration’ not loaded because @ConditionalOnClass did not find required class ‘io.lettuce.core.RedisClient’

      - test

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 1, 2020

        Hi, Thanks for the article, I didn’t test your code but I noticed that you didn’t mention the configuration class where you set up the JedisConnectionFactory and redisTemplate, that’s why, I thought, the guys got the exception above.

        - El Mehdi LAGHRAOUI

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 4, 2020

          Nice tutorial. One scenario…say in your application I updated the user id 2, with follower less than 12000, in that case ideally, when we will try to get id 2 again, it should fetch from db, instead cache. since we want only those users to be cached, whose follower is more than 12000. But your application doesn’t do that, even if you updated your user 2 with follower less than 12000, still it will be fetched from cache, instead DB. How to achieve that? Thanks for the tutorial again!

          - Souvik

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            January 3, 2020

            Its seems like you are not using redis cache. Can you put some performance improvement results or any other proof for using cache?

            - john

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 3, 2019

              The user repository is also not correct. It should be like this @Repository interface UserRepository extends JpaRepository { }

              - Ganesh Sahu

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 1, 2019

                have you used really redis cache in this app? if i am running the redis cli cmd for getting the keys from cache i don get it. what is the purpose of h2 DB here…

                - Mahesh

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 4, 2019

                  It works perfectly fine for me. Not sure why people are facing issue with this approach.

                  - RamPrakash

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    March 29, 2019

                    did you really use Redis cache ? I dont think

                    - Ajay

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel