From Hell To Heaven: Increase app’s performance with Redis

Welcome to my new series “From Hell To Heaven“. These series will be about different cases of programmers dealing with issues that anyone can find in a typical day. In this first post, we will be implementing Redis as a second level cache layer using Spring Boot.

Introduction

I have been working on a couple of projects and encountered several performance issues. This issue relied mostly on reading the same data multiple times in the same endpoint. Using second layer cache is a common solution to this issue and that’s what we are going to do today! You will see how easy it will be to integrate Redis as a cache layer using Spring boot.

What is Redis?

Redis is an in-memory data structure used as a database or cache. Being in-memory provides a huge benefit in performance; reading and writing are way faster than persisting to disk. It also provides a way of persisting data utilizing RDB and AOF, making it perfect to keep the data when restarting the server.

Implementation

Dependencies and Configuration

Your project will need spring-boot-starter-data-redis dependency in order to work properly with Spring Boot. Then we need to configure Redis and the cache, which is fairly easy to do it by taking advantage of Spring Boot’s auto configuration as shown in the following segment:

spring.redis.url=redis://user:password@example.com:6379 spring.redis.host=localhost # Redis server host. spring.redis.password= # Login password of the redis server. Leave empty if no password spring.redis.port=6379 # Redis server port. spring.cache.type=redis spring.cache.redis.cache-null-values=true # Allow caching null values. spring.cache.redis.key-prefix=project_key # Key prefix. spring.cache.redis.time-to-live=60000ms # Entry expiration. By default the entries never expire. spring.cache.redis.use-key-prefix=true # Whether to use the key prefix when writing to Redis. Read more...