Spring Boot With Redis Cache Using Annotation

Rohit Kavthekar
9 min readFeb 9, 2021

--

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 an API for showing products, offers, categories on the home page of our application. If we created these APIs 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 the performance of the website decreases, loading time increases, load on the server as well as database, etc. So in that case, If we added caching for APIs, then only for the 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 the database, data will be directly fetched from cache (in-memory store), application response time will be increased and we can give a faster user experience.

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

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 storeLoaded: 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 the 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);
}
}

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.

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.

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

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.

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.

Check the redis-cli monitor logs in the terminal.

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.

We can see the below logs in redis-cli as the user record is deleted for id.

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.

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.

Thank you for reading! You can find the working code at GitHub Repository.

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

Originally published at https://www.mindbowser.com on February 9, 2021.

--

--

Rohit Kavthekar

Full Stack Developer (Java | Angular), Passionate about writing clean, optimized code.