Spring Data Redis CRUD Operations example with Spring Boot

spring-data-springjpa-crud-operation-redis-example-spring-boot-redis-example-feature-image

Redis is an open-source, in-memory key-value data store, used as a database, cache, and message broker. In this tutorial, we’re gonna look at how to do Redis CRUD Operations with Spring Boot using Spring Data Redis.

Related Post: Spring Data Redis Messaging – PubSub example | Spring Boot

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.9.0.RELEASE
– Spring Boot: 1.5.9.RELEASE

II. Spring Data Redis

1. Maven Dependency

	org.springframework.boot
	spring-boot-starter-data-redis

2. Redis Configuration

We use Jedis as a Redis client to define and establish the connection between our Spring Boot application and the Redis server instance.

@Bean
JedisConnectionFactory jedisConnectionFactory() {
	return new JedisConnectionFactory();
}

@Bean
public RedisTemplate redisTemplate() {
	final RedisTemplate template = new RedisTemplate();
	template.setConnectionFactory(jedisConnectionFactory());
	template.setValueSerializer(new GenericToStringSerializer(Object.class));
	return template;
}

If we wanna configure connection details, just modify the jedisConnectionFactory configuration:

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
    jedisConFactory.setHostName("localhost");
    jedisConFactory.setPort(6379);
    return jedisConFactory;
}
3. Redis CRUD Operations with RedisTemplate

RedisTemplate provides DefaultHashOperations instance that can do hash-related operations for data manipulation.
To get DefaultHashOperations instance, we call RedisTemplate.opsForHash():

RedisTemplate redisTemplate;
// HashOperations
HashOperations hashOperations;

//...
hashOperations = redisTemplate.opsForHash();

// save(Customer customer)
	hashOperations.put(KEY, customer.getId(), customer);

// Customer find(Long id)
	return hashOperations.get(KEY, id);

// Map findAll()
	return hashOperations.entries(KEY);

// update(Customer customer)
	hashOperations.put(KEY, customer.getId(), customer);

// void delete(Long id)
	hashOperations.delete(KEY, id);

III. Practice

1. Project Structure

spring-data-redis-crud-structure

Customer is a Data Model Class.
CustomerRepository is an interface which will be autowired in WebController for implementing repository methods and custom finder methods.
WebController is a REST Controller which has request mapping methods for RESTful requests such as: save, findall, findbyid, update, delete.
RedisConfig defines and establishes the connection between our Spring Boot application and the Redis server instance.
Dependencies for Spring Boot and Spring Data Redis in pom.xml

2. Step by Step
1. Create Spring Boot project & add Dependencies

	org.springframework.boot
	spring-boot-starter-data-redis



	org.springframework.boot
	spring-boot-starter-web

2. Configure Spring Data Redis

Under package config, create RedisConfig class:

package com.javasampleapproach.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

@Configuration
@ComponentScan("com.javasampleapproach.redis")
public class RedisConfig {

	@Bean
	JedisConnectionFactory jedisConnectionFactory() {
		return new JedisConnectionFactory();
	}

	@Bean
	public RedisTemplate redisTemplate() {
		final RedisTemplate template = new RedisTemplate();
		template.setConnectionFactory(jedisConnectionFactory());
		template.setValueSerializer(new GenericToStringSerializer(Object.class));
		return template;
	}
}
3. Create DataModel Class

Under package model, create Customer class:

package com.javasampleapproach.redis.model;

import java.io.Serializable;

public class Customer implements Serializable {

	private static final long serialVersionUID = 1L;

	private long id;
	private String firstName;
	private String lastName;

	protected Customer() {
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Customer(long id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
	}
}
4. Create Repository

This interface helps us do all CRUD functions:

package com.javasampleapproach.redis.repo;

import java.util.Map;

import com.javasampleapproach.redis.model.Customer;

public interface CustomerRepository {

	void save(Customer customer);
	Customer find(Long id);
	Map findAll();
	void update(Customer customer);
	void delete(Long id);
}

And its implementation:

package com.javasampleapproach.redis.repo;

import java.util.Map;

import javax.annotation.PostConstruct;

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.javasampleapproach.redis.model.Customer;

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {

	private static final String KEY = "Customer";

	private RedisTemplate redisTemplate;
	private HashOperations hashOperations;

	@Autowired
	public CustomerRepositoryImpl(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@PostConstruct
	private void init() {
		hashOperations = redisTemplate.opsForHash();
	}

	@Override
	public void save(Customer customer) {
		hashOperations.put(KEY, customer.getId(), customer);
	}

	@Override
	public Customer find(Long id) {
		return hashOperations.get(KEY, id);
	}

	@Override
	public Map findAll() {
		return hashOperations.entries(KEY);
	}

	@Override
	public void update(Customer customer) {
		hashOperations.put(KEY, customer.getId(), customer);
	}

	@Override
	public void delete(Long id) {
		hashOperations.delete(KEY, id);
	}

}
5. Create Web Controller

The controller receives requests from client, using repository to do CRUD Operations and return results:

package com.javasampleapproach.redis.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.redis.model.Customer;
import com.javasampleapproach.redis.repo.CustomerRepository;

@RestController
public class WebController {

	@Autowired
	private CustomerRepository customerRepository;

	@RequestMapping("/save")
	public String save() {
		// save a single Customer
		customerRepository.save(new Customer(1, "Jack", "Smith"));
		customerRepository.save(new Customer(2, "Adam", "Johnson"));
		customerRepository.save(new Customer(3, "Kim", "Smith"));
		customerRepository.save(new Customer(4, "David", "Williams"));
		customerRepository.save(new Customer(5, "Peter", "Davis"));

		return "Done";
	}

	@RequestMapping("/findall")
	public String findAll() {
		String result = "";
		Map customers = customerRepository.findAll();

		for (Customer customer : customers.values()) {
			result += customer.toString() + "
"; } return result; } @RequestMapping("/find") public String findById(@RequestParam("id") Long id) { String result = ""; result = customerRepository.find(id).toString(); return result; } @RequestMapping(value = "/uppercase") public String postCustomer(@RequestParam("id") Long id) { Customer customer = customerRepository.find(id); customer.setFirstName(customer.getFirstName().toUpperCase()); customer.setLastName(customer.getLastName().toUpperCase()); customerRepository.update(customer); return "Done"; } @RequestMapping("/delete") public String deleteById(@RequestParam("id") Long id) { customerRepository.delete(id); return "Done"; } }
6. Run Spring Boot Application & Check Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Request 1
http://localhost:8080/save
The browser returns Done.

Request 2
http://localhost:8080/findall
spring-data-redis-crud-result-findall

Request 3
http://localhost:8080/find?id=2
spring-data-redis-crud-result-findbyid

Request 4.1
http://localhost:8080/uppercase?id=2
The browser returns Done.

>> Request 4.2: check update
http://localhost:8080/find?id=2
spring-data-redis-crud-result-update

Request 5.1
http://localhost:8080/delete?id=3
The browser returns Done.

>> Request 5.2: check delete
http://localhost:8080/findall
spring-data-redis-crud-result-delete

IV. Source Code

SpringDataRedis



By grokonez | December 31, 2017.

Last updated on September 4, 2018.



Related Posts


6 thoughts on “Spring Data Redis CRUD Operations example with Spring Boot”

  1. Excellent !!

    If possible can you please same example with Redis as a cache and MySQL as a standalone database

  2. How to find the complex query userRepository.findByMiddleNameContaining(“Li”) which doesn’t works with the Spring Data Redis?

  3. Hi,

    There was an unexpected error (type=Internal Server Error, status=500).
    Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

    Getting the above Error

  4. *** This has been deprecated ***

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
        jedisConFactory.setHostName("localhost");
        jedisConFactory.setPort(6379);
        return jedisConFactory;
    }
    
    
    *** As of Spring Data 2.0, this works ***
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
        redisStandaloneConfiguration.setPassword(RedisPassword.of("yourRedisPasswordIfAny"));
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }
    

    Rerefence: https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/connection/jedis/JedisConnectionFactory.html#setHostName-java.lang.String-

Got Something To Say:

Your email address will not be published. Required fields are marked *

*