Spring Boot With Redis Cache Using Annotation

In this article, we will be creating a simple CRUD spring boot application and integrating it with Redis Cache using annotations.

Let’s consider a scenario, we are building a web application for an e-commerce platform. We have created API’s for showing products, offers, categories on the home page of our application. If we created these API’s without using any cache then every time a request will come, data will be fetched from the database. In that case, If our application is being used by millions of users at a time then we can face multiple issues like performance of website decreases, loading time increases, load on server as well as database etc. So in that case If we added caching for API’s, then only for first request data will be fetched from the database. Whenever other requests will come data will be directly served from Cache. In this, there will be no execution of query on database, data will be directly fetched from cache (in-memory store), application response time will be increased and we can give faster user experience.

Above is the one scenario we discussed, but there are multiple scenarios in which we can use caching for that.

Check Out What It Takes To Build A Successful App Here

Before going further in this article we will look at common terminologies like Redis and Jedis.

Redis

Redis, which stands for Remote Dictionary Server, is an open-source in-memory data store written in C. It’s often used as a database, cache, and may be used as a message broker.

Data is going to be stored in Redis within the simple key-value pairs where the key is used to extract values. Redis allows us to store different types of data structures like strings, lists, maps, sets, bitmaps, streams, spatial indexes.

Redis is usually used for cache management by microservices to reduce the number of database calls to the server.

Jedis

To define connections settings from application client to Redis server, we need Redis client which will be helpful to interact with Redis server; it’s something similar to JdbcTemplate to connect with MySql Server.

Prerequisites

Installing Redis

You can easily set up a Redis server on the machine using the following command

Ubuntu 18.04 LTS & 20.04 LTS

$ sudo apt install redis-server

macOS, you can install it via brew.

$ brew install redis

After successfully installing the redis-server package, let’s check the status of the Redis process to verify the installation:

$ sudo systemctl status redis

The result shows the status of the redis-server, the bind-address and the port on which redis-server is listening on:

redis-server.service - Advanced key-value store

   Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)`

   Active: active (running) since Tue 2020-01-19 10:06:30 UTC; 3min 2s ago

     Docs: http://redis.io/documentation,

           man:redis-server(1)

 Main PID: 2227 (redis-server)

    Tasks: 4 (limit: 1152)

   CGroup: /system.slice/redis-server.service

           └─2227 /usr/bin/redis-server 127.0.0.1:6379

By default, the Redis configuration will be available in the /etc/redis/redis.conf file.

Enable Remote Connection to Redis

By default, Redis is accessible only from localhost. To enable remote connection to our Redis server, update the bind-address in Redis configuration to 0.0.0.0:

bind 0.0.0.0 ::1

Once updated, restart it:

$ systemctl restart redis

Spring Boot Redis Project Setup

We can use spring-boot-starter-data-redis maven artifact provided by Spring boot to integrate Redis with the spring boot project. Below are the maven dependencies that we require for the integration.

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

<dependency>

<groupId>redis.clients</groupId>

<artifactId>jedis</artifactId>

</dependency>

We need to configure spring data redis in the application.properties file for hostname, port number

spring.redis.host=127.0.0.1

spring.redis.port=6379

spring.cache.redis.cache-null-values=false

spring.cache.redis.time-to-live=600000

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

@SpringBootApplication

@EnableCaching

public class SpringBootRedisExampleApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBootRedisExampleApplication.class, args);

}

}

We Build the Meditation Application for a Non-Profit Organization

Defining the Entity

Create a simple User class that includes first name, last name, email and mobile. Added Lombok dependency. It is providing helpful annotations like @NoArgsConstructor, @AllArgsConstructor, and @Data instead of generating getters and setters in our code itself.

User.java
@Entity

@DynamicUpdate

@Data

@NoArgsConstructor

public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "user_id")

private Integer userId;

@Column(name = "first_name")

private String firstName;

@Column(name = "last_name")

private String lastName;

@Column(name = "email")

private String email;

@Column(name = "mobile")

private String mobile;

}

Define Controller

In that UserDto class is a simple model class that includes only getters. Always use a model class to accept the request body rather than an entity class.

UserController.java
@RestController

public class UserController {

@Autowired

private UserService userService;

@PostMapping("add-user")

public ResponseEntity<UserModel> addUser(@RequestBody UserDto userDto) {

UserModel userModel = userService.addUser(userDto);

return new ResponseEntity<UserModel>(userModel, HttpStatus.OK);

}

@GetMapping("users/{userId}")

public ResponseEntity<UserModel> getUser(@PathVariable Integer userId) {

UserModel userModel = userService.getUser(userId);

return new ResponseEntity<UserModel>(userModel, HttpStatus.OK);

}

@DeleteMapping("users/{userId}")

public ResponseEntity<String> deleteUser(@PathVariable Integer userId) {

userService.deleteUser(userId);

return new ResponseEntity<String>("User deleted successfully", HttpStatus.OK);

}

@GetMapping("users")

public ResponseEntity<List<UserModel>> allUsers(@RequestParam(defaultValue = "1") Integer page) {

List<UserModel> userModels = userService.allUsers(page);

return new ResponseEntity<List<UserModel>>(userModels, HttpStatus.OK);

}

}

UserDto.java

@Getter

public class UserDto {

private String firstName;

private String lastName;

private String email;

private String mobile;

}

Define Service

We will create a custom mapper class for converting a source class object to a destination class object. Added ModelMapper dependency for that. You can use any other dependency for doing the conversion.

UserServiceImpl.java
@Service

public class UserServiceImpl implements UserService {

@Autowired

private UserDao userDao;

@Autowired

private Mapper mapper;

@Override

public UserModel addUser(UserDto userDto) {

User user = mapper.convert(userDto, User.class);

return mapper.convert(userDao.saveUser(user), UserModel.class);

}

@Override

public UserModel getUser(Integer userId) {

User user = userDao.userById(userId);

return mapper.convert(user, UserModel.class);

}

@Override

public void deleteUser(Integer userId) {

userDao.deleteUser(userId);

}

@Override

public List<UserModel> allUsers(Integer page) {

return mapper.convertToList(userDao.allUsers(page), UserModel.class);

}

}

Mapper.java

@Component

public class Mapper {

public <T> T convert(Object srcObj, Class<T> targetClass) {

T response = null;

ModelMapper modelMapper = new ModelMapper();

modelMapper.getConfiguration().setAmbiguityIgnored(true);

try {

response = modelMapper.map(srcObj, targetClass);

} catch (Exception e) {

throw new CustomException(e.getMessage(), 500);

}

return response;

}

public <S, T> List<T> convertToList(List<S> srcList, Class<T> targetClass) {

List<T> response = new ArrayList<>();

ModelMapper modelMapper = new ModelMapper();

modelMapper.getConfiguration().setAmbiguityIgnored(true);

try {

srcList.stream().forEach(source -> response.add(modelMapper.map(source, targetClass)));

} catch (Exception e) {

throw new CustomException(e.getMessage(), 500);

}

return response;

}

}

Define DAO layer

We will add caching in the DAO layer using @CachePut, @CacheEvict, @Cacheable, @Caching annotations.

The reason we are going to use the DAO layer for caching is that sometimes we need to do some operations on results in the service layer based on parameters passed or we can call the same methods from different locations. It’s better to maintain a separate DAO layer for caching purposes and others too.

Let’s see how to add caching on methods.

Case 1: Add and Get User

First, we will create two methods one is for adding users and the other is for getting users by id.

@Override

@Caching(evict = { @CacheEvict(value = "usersList", allEntries = true), }, put = {

@CachePut(value = "user", key = "#user.getUserId()") })

public User saveUser(User user) {

try {

return userRepo.save(user);

} catch (Exception e) {

throw new CustomException("Error while saving user", 500);

}

}

@Override

@Cacheable(value = "user", key = "#userId")

public User userById(Integer userId) {

return userRepo.findByUserId(userId).orElseThrow(() -> new CustomException("User not found", 400));

}

In the saveUser() method, We have added @CachePut annotation for updating or adding the particular entity in the cache, and @CacheEvict is used because If we have created a cache for users list then if the user is updated or deleted then we are going to evict or flush the cache with the given value to makes sure that it should also update in Redis Cache.

In the userById() method, we have used @Cacheable annotation with key as “userId” and value as “user”. So that when this method is called, a record of the user with userId will be stored in Redis cache.

So, Let’s see this by calling the API from Postman.

Before calling add-user API first open the terminal and run the below command to view whether the record is inserted in the Redis cache or not.

$ redis-cli monitor

Call the add-user API from the postman with the user required fields.

Spring Boot with Redis Cache using annotation

After calling the API we will be able to see the logs below in redis-cli monitor. That means the record is successfully added to the Redis cache with given key and values.

You can see the “SET” operation with value and key as “user::1”. It means the user is stored in Redis cache.

Spring Boot with Redis Cache using annotation

Now we will call “users/{userId}” ex. “users/1” API to get the user details by Id.

Spring Boot with Redis Cache using annotation

In redis-cli logs, We can see the “GET” operation with key-value as “user::1”.

There is no “SET” operation performed. But when you explicitly run the redis-cli flushall command or cache expires then after calling the same API, the first “SET” operation is called, and then the “GET” operation is called.

Spring Boot with Redis Cache using annotation

Case 2: Users List with Pagination

Consider there are thousands of records in the database and you want to return the records based on the pagination. In that case, we will do caching for a list of records using the key as page number and value as usersList.

By doing so we can achieve a faster response in terms of accessing records on the basis of pagination.

For this, we will create a method that will return a list of users.

@Override

@Cacheable(value = "usersList", key = "#page")

public List<User> allUsers(Integer page) {

Page<User> users = userRepo.findAll(PageRequest.of(--page, 5));

if (users.isEmpty()) {

throw new CustomException("Users not found", 400);

}

return users.getContent();

}

In the above method, we have added @Cacheable annotation with value as “usersList” and key as “page”.

Now let’s call the users list API.

Spring Boot with Redis Cache using annotation

Check the redis-cli monitor logs in the terminal.

Spring Boot with Redis Cache using annotation

Case 3: Delete user

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

@Override

@Caching(evict = { @CacheEvict(value = "usersList", allEntries = true),

@CacheEvict(value = "user", key = "#userId"), })

public void deleteUser(Integer userId) {

try {

userRepo.deleteById(userId);

} catch (Exception e) {

throw new CustomException("Error while deleting user", 500);

}

}

In the deleteUser() method, we have added an array of @CacheEvict  as we have maintained a users list array. 

Let’s do this by calling delete user API.
Spring Boot with Redis Cache using annotation

We can see below logs in redis-cli as the user record is deleted for id.
Spring Boot with Redis Cache using annotation

Key Points to Remember

  • Define TTLs : Time-to-live (TTL), is the time span after which your Cache will be deleting an entry. If you want to fetch data only once a minute, just guard it with a @Cacheable Annotation and set the TTL to 1 minute.
  • Implement Serializable: If you are adding an object in Redis cache then the object should implement a Serializable interface.
  • Redis Cache Limits: When cache size reaches the memory limit, old data is removed to make a place for a new one. 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.
  • Never Call Cacheable Method from the same class: The reason is that Spring proxy the access to these methods to make the Cache Abstraction work. When you call it within the same class this Proxy mechanic is not kicking in. By this, you basically bypass your Cache and make it non-effective.
  • Use Lettuce, If you need something highly scalable: Lettuce is a scalable thread-safe, non-blocking Redis client based on netty and Reactor. Jedis is easy to use and supports a vast number of Redis features, however, it is not thread-safe and needs connection pooling to work in a multi-threaded environment.
coma

Conclusion

We learned a lot in this article. We installed the Redis server on a machine, we have created a spring boot application using annotations like @Cacheable, @Caching, @CachePut, and @CacheEvict.

In case you have some questions feel free to write to us 🙂

Bring the best talent onboard only when you require, Hire Java Developers with unparalleled Flexibility

Rohit

Full Stack Developer (Java | Angular)

Rohit is having 2.8 years of experience as a Full Stack Developer. He has good knowledge of creating APIs, well-designed microservices, payment gateway integrations and web technology like Angular 4+. He is a passionate coder who writes clean, optimized code. In his free time, he does solve technical problems on hacker rank, StackOverflow, geeks for geeks etc.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks