Introduction

We have different cache techniques in this software industry. We will have a small talk about Redis Cache.

We use cache service to improve the API response means we save the response in the cache for a duration and response is sent back from cache instead of real service/databases.

  • Reduces the backend API calls / Database calls.
  • Reduces loads on the blackened server.

Let’s Try:

Let’s Start on Redis container part. 

We can run a Redis docker container in your system as a local instance. You can go through the Create and Run Redis Container.

If you don’t have docker installed, You can go through the local Redis Set Up Link.

Let’s start with a sample Spring Boot Project. 

How to create a Spring Boot Project with maven?? You can go through the Link to create Spring Boot Project from Scratch

Create a Spring Boot Project from Spring Initializr with maven as a dependency manager. Also, include Spring Web dependencies. 

pom.xml 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>spring-redis-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-redis-demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

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

</project>

Once you update Pom.xml . You will get all the dependencies will be downloaded and included to project.

Below would be the Spring Main Application class .

package com.example.springredisdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SpringRedisDemoApplication {

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


    @Bean
    JedisConnectionFactory jedisConnectionFactory(Environment env) {

        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(env.getProperty("localhost"));
        redisStandaloneConfiguration.setPort(6379);
        return new JedisConnectionFactory(redisStandaloneConfiguration);

    }

    @Bean
    RedisTemplate<String, String> redisTemplate(Environment env) {

        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory(env));
        return redisTemplate;

    }
}

You need to creates Beans to connect to Redis container and do operations on Redis.

In above program, we have created two beans

  1. To create connection “JedisConnectionFactory”.
  2. To do operation on Redis “RedisTemplate

Now the beans are ready. You can use these beans in you program wherever you want to have caching operation.

You can include the “RedisTemplate” like below in your Service layer (@Service) for operation.

@Autowired
    RedisTemplate redisTemplate;

For Caching the data you need to use the bean below way ,

redisTemplate.opsForHash().put("UniqueKey","HttpBin.Org",response_to_cache);

For setting Expiry to the cached key , below code would be helpful.

redisTemplate.expire("UniqueKey",60, TimeUnit.SECONDS);

Above Code means, the Redis will hold this key and its value till 60 seconds. After that, It deletes the Key.

Above code will set TTL (Time To Live) to 60 seconds in Redis Cache against the Key.