Spring Data Redis Example

As you’ve read about Redis Installation & Configuration, you’re mostly understand the main concept of Redis database. Redis is an extremely high-performed, lightweight data store. It provides key/value data access to persistent byte arrays, lists, sets and hash data structures. So, the insertion, deletion and retrieve operations inside Redis becomes very simple how we have worked with using of Map, List , Set and an Array data structures how it is used inside normal Java program; although some minimal modifications that you’ve probably never care about them.

As you’ve been doing once it comes to deal with any database platform, you have to download/install the database driver. For Redis four driver libraries are provided for allowing your application to get connected to Redis. Spring Data supports connecting to Redis using either the Jedis (That will be considered in this tutorial), JRedis, RJC or SRP driver libraries. It doesn’t matter which library have been used, cause the Spring Data has abstracted the differences between those drivers into common set of APIs and template-style helpers.

1. Spring Context Configuration

To connect to Redis using Jedis, you need to create an instance of org.springframework.data.redis.connection.jedis.JedisConnectionFactory. The other driver libraries have corresponding ConnectionFactory subclasses. Below the proper Spring Context (SpringContext.xml) that should be used for initializing and connecting the Redis database through using of Spring.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!--  Scanning the Spring Beans -->
	<context:component-scan base-package="net.javabeat.springdata.beans"></context:component-scan>
	<!-- Redis Connection Factory -->
	<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
			p:use-pool="true" />
	<!-- Redis Template -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
			p:connection-factory-ref="jedisConnFactory" />

  • For searching about all Spring component (beans), you’ve provided the component-scan element.
  • For connecting the Redis database, you’ve provided the Jedis connection factory bean.
  • The central abstraction you’re likely to use when accessing Redis via Spring Data Redis is the org.springframework.data.redis.core.RedisTemplate class.

Since the feature set of Redis is really too large to effectively encapsulate into a single class, the various operations on data are split into separate operations classes as follows:

  • ValueOperations:Returns the operations performed on simple values (or Strings in Redis terminology.
  • ListOperations:Returns the operations performed on list values.
  • SetOperations:Returns the operations performed on set values.
  • ZSetOperations:Returns the operations performed on zset values (also known as sorted sets.
  • HashOperations:Returns the operations performed on hash values.
  • BoundValueOperations:Returns the operations performed on hash values bound to the given key.
  • BoundListOperations:Returns the operations performed on list values bound to the given key.
  • BoundSetOperations:Returns the operations performed on set values bound to the given key.
  • BoundZSetoperations:Returns the operations performed on zset values (also known as sorted sets) bound to the given key.
  • BoundHashOperations:Returns the operations performed on hash values bound to the given key.

2. Maven Dependencies for Spring Data Redis

The required libraries and dependencies for making the connecting of Redis is achievable are listed inside the below pom.xml file.


<?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">
	<name>Spring Data</name>
		<!-- SLF4J dependency -->
		<!-- Spring Data - Redis Library -->
		<!-- Jedis Driver Library -->
		<!-- Spring Core -->
		<!-- Spring Data commons -->

3. Spring Beans (RegisterationBean)

For accessing the RedisTemplate that defined above, you have to use @Autowired annotation for being RedisTemplate available at your Spring Beans.


package net.javabeat.springdata.beans;

import net.javabeat.springdata.jpa.data.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

public class RegistrationBean {
	private RedisTemplate<String,User> redisTemplate;

	public RedisTemplate<String, User> getRedisTemplate() {
		return redisTemplate;

	public void setRedisTemplate(RedisTemplate<String, User> redisTemplate) {
		this.redisTemplate = redisTemplate;

4. Java Beans

The business domain is very simple, it’s just a User entity associated with an instance of Address. Look below.


package net.javabeat.springdata.jpa.data;

import java.io.Serializable;

public class User implements Serializable{

	private static final long serialVersionUID = 1L;

	private String id;

	private String fullName;

	private String age;

	private String status;

	private Address address;

	public String getFullName() {
		return fullName;

	public void setFullName(String fullName) {
		this.fullName = fullName;

	public String getAge() {
		return age;

	public void setAge(String age) {
		this.age = age;

	public String getStatus() {
		return status;

	public void setStatus(String status) {
		this.status = status;

	public String getId() {
		return id;

	public void setId(String id) {
		this.id = id;

	public Address getAddress() {
		return address;

	public void setAddress(Address address) {
		this.address = address;

	public String toString() {
		return this.id + "," + this.fullName;


package net.javabeat.springdata.jpa.data;

import java.io.Serializable;

public class Address implements Serializable{

	private static final long serialVersionUID = 1L;

	private Long addressId;

	private String addressValue;

	public Long getAddressId() {
		return addressId;
	public void setAddressId(Long addressId) {
		this.addressId = addressId;
	public String getAddressValue() {
		return addressValue;
	public void setAddressValue(String addressValue) {
		this.addressValue = addressValue;

5. Spring Data Redis Example Application

The below Java Class, is just an executable application that developed for persisting an User entity associated with an Address inside Redis key/value database. Note that the using of this concept entity is just theoretical uses and it doesn’t mean anything when it comes to apply it inside the Redis.


package net.javabeat.springdata.executable;

import net.javabeat.springdata.beans.RegistrationBean;
import net.javabeat.springdata.jpa.data.Address;
import net.javabeat.springdata.jpa.data.User;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Executable {
	public static RegistrationBean registrationBean;
	public static ClassPathXmlApplicationContext context;

	static {
		// Acquire Context
		context = new ClassPathXmlApplicationContext("SpringContext.xml");

	public static void main(String [] args) throws Exception{
		// Create User

	public static void createUser(){
		User user = new User();
		user.setFullName("Susa Richard");
		Address address = new Address();
		RegistrationBean bean = (RegistrationBean)context.getBean("registrationBean");
		// Persisting Inside the Hash User object
		bean.getRedisTemplate().opsForHash().put("UserA", user.hashCode(),user);
		// Retrieving the User object from the Redis by using the suggested key
		User x = (User)bean.getRedisTemplate().opsForHash().get("UserA", user.hashCode());

6. Query Redis Persisted Store

The below snapshot shows you the User object that already persisted inside the Hash persistent store inside the Redis Key/Value database.Redis Persisted Data


Spring Data provides the Spring Developer an abstracted, simplest and modeled integrating way for communicating with the Redis database. Regardless of the driver library that the developer had used, Spring Data still able to operate upon Redis in a standard manner and that’s because the RedisTemplate Spring Data facility. By using the RedisTemplate, the developer is capable of invoking all of defined operations regarding the different persistent stores that provided by Redis.

Download Source Code

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>