Spring Boot Redis Data Example CRUD Operations

By | 2018-11-11T12:04:44+05:30 October 18th, 2018|Spring Boot|1 Comment

In this tutorials, I am going to introduce a most popular in-memory data store spring boot redis.

In the previous tutorial, we discussed what is redis 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 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 redisserver, 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
  • Jedis
  • Java8
  • Maven

redis and jedis specific dependencies:

Below are the redis and jedis maven dependencies.


Application Structure:

Spring Boot Redis example crud

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">


  <description>Spring Boot Redis Example</description>

    <relativePath/> <!-- lookup parent from repository -->




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;

public class ItemController {
    ItemRepository itemRepo;

    public ResponseEntity<Map<Integer,Item>> getAllItems(){
        Map<Integer,Item> items =  itemRepo.getAllItems();
        return new ResponseEntity<Map<Integer,Item>>(items, HttpStatus.OK);

    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"})
    public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<Item>(headers, HttpStatus.CREATED);

    public ResponseEntity<Item> updateItem(@RequestBody Item item){
        if(item != null){
        return new ResponseEntity<Item>(item, HttpStatus.OK);

    public ResponseEntity<Void> deleteItem(@PathVariable int 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 in 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;

public class SpringBootRedisExample {

  JedisConnectionFactory jedisConnectionFactory(){
    return new JedisConnectionFactory();

  RedisTemplate<String, Item> redisTemplate(){
    RedisTemplate<String,Item> redisTemplate = new RedisTemplate<String, Item>();
    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 and etc.

If you wanted to provide your application-specific configuration, you can even freely configure it like below.

public JedisConnectionFactory connectionFactory() {
  JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
  return connectionFactory;

Creating Item Repository, it is responsible to read and write data into reris 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;

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){

    /*delete an item from database*/
    public void deleteItem(int id){

    /*update an item from database*/
    public void updateItem(Item item){

Note: Redis supports various operations on data such as list, set, hash, gio, value and etc. So that it provides a specific subinterface to deal with each operation. As we are dealing with Item class, we can opt for opsForhash().

opsForHash() gives the hashOperations instance, it provides different methods to read/write data into redis server.

Run the Application:

Note: Start redisserver on your machine and follow the below scenarios.

Accessing the application from the postman, and adding an item using POST request.

Spring Boot Redis example crud output create

Getting all items from redis

Spring Boot Redis example crud output getAll

updating Item -3

Spring Boot Redis example crud output update

After updating Item -3

Spring Boot Redis example crud output getAll After Update

Deleting Item -3

Spring Boot Redis example crud output Delete


Spring Data Redis Docs

Install Redis on windows

Happy Learning 🙂

Download Example

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

One Comment

  1. yaghobabbasi09@gmail.com'
    yaghob February 18, 2019 at 1:12 pm - Reply

    Hi dear this learning is so valuable and many thanks,
    but when i start application i get this error:
    ConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.
    i hope give recommendation tome.

Leave A Comment