Spring Boot Redis Data Example CRUD Operations - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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.
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.
A simple example to understand Spring boot data redis.
Spring Boot 2.0.5
Spring Boot Data Redis
Redis server 2.4.5
Jedis
Java8
Maven
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>
<?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 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.
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
Spring Data Redis Docs
Install Redis on windows
Happy Learning 🙂

Spring Boot JdbcTemplate CRUD Operations Mysql
Spring boot exception handling rest service (CRUD) operations
Spring Boot How to change the Tomcat to Jetty Server
How to change Spring Boot Tomcat Port Number
Simple Spring Boot Example
Spring Boot MockMvc JUnit Test Example
MicroServices Spring Boot Eureka Server Example
How to use Spring Boot Random Port
Spring Boot Redis Cache Example – Redis Server
How to set Spring Boot SetTimeZone
Spring Boot JNDI Configuration – External Tomcat
Spring Boot MongoDB + Spring Data Example
Spring Boot Multiple Data Sources Example
Setup/Install Redis Server on Windows 10
Spring Boot DataRest Example RepositoryRestResource

Spring Boot JdbcTemplate CRUD Operations Mysql
Spring boot exception handling rest service (CRUD) operations
Spring Boot How to change the Tomcat to Jetty Server
How to change Spring Boot Tomcat Port Number
Simple Spring Boot Example
Spring Boot MockMvc JUnit Test Example
MicroServices Spring Boot Eureka Server Example
How to use Spring Boot Random Port
Spring Boot Redis Cache Example – Redis Server
How to set Spring Boot SetTimeZone
Spring Boot JNDI Configuration – External Tomcat
Spring Boot MongoDB + Spring Data Example
Spring Boot Multiple Data Sources Example
Setup/Install Redis Server on Windows 10
Spring Boot DataRest Example RepositoryRestResource






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.









Adriano
August 8, 2020 at 6:41 am - Reply 

Great Sample! I spent some time searching for a sample like yours.
Tks a lot!










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.




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.





Adriano
August 8, 2020 at 6:41 am - Reply 

Great Sample! I spent some time searching for a sample like yours.
Tks a lot!




Great Sample! I spent some time searching for a sample like yours.
Tks a lot!
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment