Spring Boot Redis Data Example CRUD Operations

By | 2018-11-11T12:04:44+00:00 October 18th, 2018|Spring Boot|0 Comments

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.

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
</dependency>

Application Structure:

Spring Boot Redis example crud

Complete project 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 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

ItemController.java
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

Item.java
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.

SpringBootRedisExample.java
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 and etc.

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

ConnectionFactory
@Bean
public JedisConnectionFactory connectionFactory() {
  JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
  connectionFactory.setHostName("somehost");
  connectionFactory.setPort(9000);
  return connectionFactory;
}

Creating Item Repository, it is responsible to read and write data into reris server using RedisTemplate.

ItemRepository.java
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);
    }
}

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

Reference:

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+ ,

Leave A Comment