In this tutorial, I am going to introduce the most popular in-memory data store spring boot redis.
In the previous tutorial, we discussed what redis is and how to install redis server on windows 10 operating system. We also talk about rediscli and done some of the basic operations on both the redis server and rediscli.
Spring Boot Redis Data :
As part of this article, I am going to implement a simple spring boot data redis application with necessary CRUD operations. To make this application up and running, initially, you should have redis server setup in your local and it should be in running mode.
What is Jedis?
To define the connection settings from the application client to Redis server, we need a redis client which will be helpful to interact with redis server; it is something similar like JdbcTemplate to connect with the SQL server.
There are several redis client implementations available in the market for Java. For this tutorial, I choose Jedis – A simple and powerful implementation for redis client.
Spring Boot Redis Data Example:
A simple example to understand Spring boot data redis.
Technologies Used:
- Spring Boot 2.0.5
- Spring Boot Data Redis
- Redis server 2.4.5
- Jedis
- Java8
- Maven
redis and Jedis specific dependencies:
Below are the redis and Jedis maven dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
Application Structure:
Complete project dependencies:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>SpringBoot-Redis-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot-Redis-Example</name>
<description>Spring Boot Redis Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Creating a simple rest controller to provide CRUD endpoints
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.repo.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
@RestController
public class ItemController {
@Autowired
ItemRepository itemRepo;
@RequestMapping("/getAllItems")
@ResponseBody
public ResponseEntity<Map<Integer,Item>> getAllItems(){
Map<Integer,Item> items = itemRepo.getAllItems();
return new ResponseEntity<Map<Integer,Item>>(items, HttpStatus.OK);
}
@GetMapping("/item/{itemId}")
@ResponseBody
public ResponseEntity<Item> getItem(@PathVariable int itemId){
Item item = itemRepo.getItem(itemId);
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@PostMapping(value = "/addItem",consumes = {"application/json"},produces = {"application/json"})
@ResponseBody
public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){
itemRepo.addItem(item);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/addItem/{id}").buildAndExpand(item.getId()).toUri());
return new ResponseEntity<Item>(headers, HttpStatus.CREATED);
}
@PutMapping("/updateItem")
@ResponseBody
public ResponseEntity<Item> updateItem(@RequestBody Item item){
if(item != null){
itemRepo.updateItem(item);
}
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@DeleteMapping("/delete/{id}")
@ResponseBody
public ResponseEntity<Void> deleteItem(@PathVariable int id){
itemRepo.deleteItem(id);
return new ResponseEntity<Void>(HttpStatus.ACCEPTED);
}
}
Creating an Item model
package com.onlinetutorialspoint.model;
import java.io.Serializable;
public class Item implements Serializable {
private int id;
private String name;
private String category;
public Item() {
}
public Item(int id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Redis Java Configuration:
Redis java configuration is as simple as defining a @Bean in spring. Initially create JedisConnectionFactory then create a RedisTemplate using JedisConnectionFacory object.
For simplicity, I am not separating this config in a different class; I am just defining beans inside the Spring boot main class.
package com.onlinetutorialspoint;
import com.onlinetutorialspoint.model.Item;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootApplication
public class SpringBootRedisExample {
@Bean
JedisConnectionFactory jedisConnectionFactory(){
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<String, Item> redisTemplate(){
RedisTemplate<String,Item> redisTemplate = new RedisTemplate<String, Item>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisExample.class, args);
}
}
On the above redisConnectionFactory() method created RedisConnectionFactory object and return it. It means the RedisConnectioFactory is created with default connection properties such as host as localhost and port as 8080, etc.
If you wanted to provide your application-specific configuration, you can even freely configure it like below.
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName("somehost");
connectionFactory.setPort(9000);
return connectionFactory;
}
Creating Item Repository, it is responsible for reading and writing data into redis server using RedisTemplate.
package com.onlinetutorialspoint.repo;
import com.onlinetutorialspoint.model.Item;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class ItemRepository {
public static final String KEY = "ITEM";
private RedisTemplate<String,Item> redisTemplate;
private HashOperations hashOperations;
public ItemRepository(RedisTemplate<String, Item> redisTemplate) {
this.redisTemplate = redisTemplate;
hashOperations = redisTemplate.opsForHash();
}
/*Getting all Items from tSable*/
public Map<Integer,Item> getAllItems(){
return hashOperations.entries(KEY);
}
/*Getting a specific item by item id from table*/
public Item getItem(int itemId){
return (Item) hashOperations.get(KEY,itemId);
}
/*Adding an item into redis database*/
public void addItem(Item item){
hashOperations.put(KEY,item.getId(),item);
}
/*delete an item from database*/
public void deleteItem(int id){
hashOperations.delete(KEY,id);
}
/*update an item from database*/
public void updateItem(Item item){
addItem(item);
}
}
As we are dealing with Item class, we can opt for opsForhash().
opsForHash() gives the hashOperations instance, and it provides different methods to read/write data into redis server.
Run the Application:
Accessing the application from the postman, and adding an item using a POST request.
Getting all items from redis
updating Item -3
After updating Item -3
Deleting Item -3
Reference:
Download Source from GIT:
Happy Learning 🙂