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.
SpringContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" 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" /> </beans>
- 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.
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>net.javabeat.springdata</groupId> <artifactId>SpringData</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>Spring Data</name> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <dependencies> <!-- SLF4J dependency --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <!-- Spring Data - Redis Library --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.2.1.RELEASE</version> </dependency> <!-- Jedis Driver Library --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.4.2</version> </dependency> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.0.RELEASE</version> </dependency> <!-- Spring Data commons --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.5.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.0.3.RELEASE</version> </dependency> </dependencies> </project>
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.
RegistrationBean.java
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; @Component public class RegistrationBean { @Autowired 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.
User.java
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; } }
Address.java
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.
Executable.java
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 createUser(); } public static void createUser(){ User user = new User(); user.setId("20011202"); user.setFullName("Susa Richard"); user.setStatus("A"); user.setAge("30"); Address address = new Address(); address.setAddressValue("UK/Manchester"); user.setAddress(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()); System.out.println(x); } }
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.
Summary
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.