Spring Boot Redis Example (2024)
In this tutorial, we'll implement Redis
crud operations in Spring Boot
application.
Q: What is Redis?
Ans:
Redis is a distributed in-memory key-value database, cache, and message broker with optional durability. Redis supports different kinds of abstract data structures, such as strings, lists, maps, sets, sorted sets, HyperLogLogs, bitmaps, streams, and spatial indexes. Redis stands for REmote DIctionary Server (Redis).
Q: What is the maximum size of key in redis?
Ans:
According to the redis official docs, the maximum size of key in redis is 512MB.
Install Redis
Follow the steps given here to install Redis Client/Server to test this application.Create Spring Boot application
Create Spring Boot application from Spring Initializr.
Project Structure
Add Dependencies
Add spring-boot-starter-data-redis
dependency in 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.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>SpringBootRedis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootRedis</name>
<description>SpringBoot Redis database Example</description>
<properties>
<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>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Take a look at our suggested posts:
Redis Configuration
- To obtain Redis connections, Spring Data provides a variety of connection factories. We'll
utilise
JedisConnectionFactory
as our connection factory in this example. - Jedis is a lightweight and easy-to-use Java Redis client.
RedisTemplate
is provided by Spring Data for performing Redis operations.- We're going to use the Jedis client, and we're going to define a
connectionFactory
. - The
jedisConnectionFactory
was then used to create a RedisTemplate. This method can be used to query data stored in a custom repository. - The main class for interacting with Redis data is
RedisTemplate
. It handles automatic serialization and deserialization between the provided objects and Redis binary data.RedisTemplate
utilises Java serialization by default. - By default,
JedisConnectionFactory
uses the host name localhost and the port 6379. - By default, RedisTemplate does not support transactions. To make it work, we must call its
method
setEnableTransactionSupport
and set totrue
.
package com.techgeeknext.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableRedisRepositories
public class RedisConfig {
@Value("${redis.host}")
private String redisHostName;
@Value("${redis.port}")
private Integer redisPort;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
redisConfig.setHostName(redisHostName);
redisConfig.setPort(redisPort);
return new JedisConnectionFactory(redisConfig);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new JdkSerializationRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
Application Properties
Add redis default host and port in application.properties
.
redis.host=localhost
redis.port=6379
Entity
- At the minimum, every domain entity must be annotated with
and have
@Id
annotated properties. - The actual key required to persist the hash is created by the
@RedisHash
and@Id
properties. - We can utilize secondary indices like
@Index
in addition to identifier properties annotated with@Id
. @Index
is a Redis index that can be used to speed up property-based searches.
package com.techgeeknext.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("Menu")
public class Menu implements Serializable {
@Id
private int id;
//Used to speed up the property based search
//@Index
//private int redisExtId;
private String item;
private long price;
}
Repository for Redis operations
- Redis Hashes are quite a useful way to store items in memory because they can hold a n number of key-value pairs and are built to consume less memory.
- We can manage redis hash values using the
HashOperations
helper class.HashOperations hashOperations = redisTemplate.opsForHash();
HashOperations
haveput(), get(), entries(), values, and delete
etc. as basic hash map operations to operate with redis hash key values.
package com.techgeeknext.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import com.techgeeknext.entity.Menu;
import java.util.List;
@Repository
public class MenuRepo {
public static final String HASH_KEY_NAME = "MENU-ITEM";
@Autowired
private RedisTemplate redisTemplate;
public Menu save(Menu menu){
// SETS menu object in MENU-ITEM hashmap at menuId key
redisTemplate.opsForHash().put(HASH_KEY_NAME,menu.getId(),menu);
return menu;
}
public List<Menu> findAll(){
// GET all Menu values
return redisTemplate.opsForHash().values(HASH_KEY_NAME);
}
public Menu findItemById(int id){
// GET menu object from MENU-ITEM hashmap by menuId key
return (Menu) redisTemplate.opsForHash().get(HASH_KEY_NAME,id);
}
public String deleteMenu(int id){
// DELETE the hashkey by menuId from MENU-ITEM hashmap
redisTemplate.opsForHash().delete(HASH_KEY_NAME,id);
return "Menu deleted successfully !!";
}
}
Controller to test Spring Boot Redis
We will use the CRUD rest endpoints and call the HashOperations
to test the redis data.
package com.techgeeknext.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.techgeeknext.entity.Menu;
import com.techgeeknext.repository.MenuRepo;
@RestController
@RequestMapping("/menu")
public class MenuController {
@Autowired
private MenuRepo menuRepo;
@PostMapping
public Menu save(@RequestBody Menu menuDetails) {
return menuRepo.save(menuDetails);
}
@GetMapping
public List<Menu> getMenus() {
return menuRepo.findAll();
}
@GetMapping("/{id}")
public Menu findMenuItemById(@PathVariable int id) {
return menuRepo.findItemById(id);
}
@DeleteMapping("/{id}")
public String deleteMenuById(@PathVariable int id) {
return menuRepo.deleteMenu(id);
}
}
Test Spring Boot Redis Example
Install Redis
Follow the steps given here to install Redis Client/Server to test this application.- Start the Redis Server using command
redis-server.exe --maxheap 1024M
. - Start the Spring Boot Application by running
spring-boot:run
or by running main class. POST data to Redis
Use POST method with end point http://localhost:8080/menu to save menu data to the redis database.GET All data from Redis
Use GET method with end point http://localhost:8080/menu to retrieve all menu data from the redis database.GET data by Id from Redis
Use GET method with end point http://localhost:8080/menu/2 to fetch menu data from the redis database by menu Id.DELETE data by Id from Redis
Use DELETE method with end point http://localhost:8080/menu/2 to delete menu data from the redis database by menu Id.
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot Redis Example