Redis is an in-memory key/value store. It is used as a database, cache and message broker. In this article, we will see some examples of Spring Data Redis. Before we get to start with the examples, we need to first install Redis and configure the server.
1. Overview of Redis
Redis is an extremely high-performance, lightweight key/value based data store. It provides several operations like persistenting byte arrays, lists, sets, and hash data structures. It also supports a way to generate atomic counters and also has an efficient topic-based pub/sub messaging functionality. It lacks in complex querying functionality. Redis servers can also be clustered together to povide distributed environment. One can interact with Redis using command line.
2. Installing Redis
- Download Redis Release. We have downloaded the release for Windows 3.0 on 64 bit.
- Download the binaries, bundled as zip file and the installer MSI file.
- Unzip the binaries to a new directory, for example,
c:\redis
. Copy the installer to the same directory. - Run the installer file and follow through the wizard.
- Once installed, redis is available as service. By default it will already be started.
3. Start Redis Manually
In case you want to start redis manually. Stop the redis service, go to the installed redis directory and run redis-server.exe
from command line.
01 | C:\redis<redis-server.exe |
02 | [5784] 06 Jan 08:46:59.903 |
03 | t config. In order to specify a config file use redis-server.exe /path/to/redis. |
07 | _.-`` `. `_. '' -._ Redis 3.0.500 (00000000/0) 64 bit |
08 | .-`` .-```. ```\/ _.,_ '' -._ |
09 | ( ' , .-` | `, ) Running in standalone mode |
10 | |`-._`-...-` __...-.``-._| '` _.-' | Port: 6379 |
11 | | `-._ `._ / _.-' | PID: 5784 |
12 | `-._ `-._ `-./ _.- ' _.-' |
13 | |`-._`-._ `-.__.- ' _.-' _.-'| |
15 | `-._ `-._`-.__.- '_.-' _.-' |
16 | |`-._`-._ `-.__.- ' _.-' _.-'| |
18 | `-._ `-._`-.__.- '_.-' _.-' |
23 | [5784] 06 Jan 08:46:59.920 |
24 | [5784] 06 Jan 08:46:59.921 * The server is now ready to accept connections on po |
4. Accessing Redis using command line
Now that we have started the server, its good time to quickly test redis. Maybe insert a key/value and retrieve it.
In order to quickly test, you can use Redis command-line shell that you can use interactively.
- Go to the installed redis directory and then run
redis-cli
from command line. - Get all the keys.
- Insert a key value.
1 | 127.0.0.1:6379< set example spring-redis |
- Get all the keys.
- Let’s now get value of “example”.
1 | 127.0.0.1:6379< get example |
5. Accessing Redis using Java
In order to connect to Redis using java, you need to first download a redis driver. You can see the redis java drives listedhere. In our examples, we will use Jedis.
Add the following dependency to your pom.xml
.
pom.xml:
2 | < groupId >redis.clients</ groupId > |
3 | < artifactId >jedis</ artifactId > |
4 | < version >2.8.0</ version > |
6. Dependencies
Since we want to use spring support for accessing redis, you also need to add spring based artifacts to pom.xml
.
Here is the complete pom.xml
.
spring-data-redis
is for the spring-redis support.spring-core
and spring-context
for spring bean and context support.commons-pool2
– Apache commons pooljedis
– Redis Java Driver
pom.xml:
03 | < modelVersion >4.0.0</ modelVersion > |
04 | < groupId >com.javacodegeeks.spring.redis</ groupId > |
05 | < artifactId >springQuartzScheduler</ artifactId > |
06 | < version >0.0.1-SNAPSHOT</ version > |
09 | < groupId >org.springframework</ groupId > |
10 | < artifactId >spring-core</ artifactId > |
11 | < version >4.1.5.RELEASE</ version > |
14 | < groupId >org.springframework</ groupId > |
15 | < artifactId >spring-context</ artifactId > |
16 | < version >4.1.5.RELEASE</ version > |
19 | < groupId >org.springframework.data</ groupId > |
20 | < artifactId >spring-data-redis</ artifactId > |
21 | < version >1.5.0.RELEASE</ version > |
24 | < groupId >org.apache.commons</ groupId > |
25 | < artifactId >commons-pool2</ artifactId > |
26 | < version >2.4.2</ version > |
29 | < groupId >redis.clients</ groupId > |
30 | < artifactId >jedis</ artifactId > |
31 | < version >2.8.0</ version > |
7. Spring Redis Configuration
To connect to Redis using Jedis, you need to create an instance oforg.springframework.data.redis.connection.jedis.JedisConnectionFactory
.
The other driver libraries have corresponding ConnectionFactory
subclasses.
SpringRedisConfig:
01 | package com.javacodegeeks.spring.redis; |
03 | import org.springframework.context.annotation.Bean; |
04 | import org.springframework.context.annotation.Configuration; |
05 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; |
06 | import org.springframework.data.redis.core.StringRedisTemplate; |
09 | public class SpringRedisConfig { |
11 | public JedisConnectionFactory connectionFactory() { |
12 | JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); |
13 | connectionFactory.setHostName( "localhost" ); |
14 | connectionFactory.setPort( 6379 ); |
15 | return connectionFactory; |
8. RedisTemplate Example
Just the way spring provides template classes, even for redis, spring provides RedisTemplate
to simplify Redis data access code.
SpringRedisConfig:
01 | package com.javacodegeeks.spring.redis; |
03 | import org.springframework.context.annotation.Bean; |
04 | import org.springframework.context.annotation.Configuration; |
05 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; |
06 | import org.springframework.data.redis.core.RedisTemplate; |
09 | public class SpringRedisConfig { |
11 | public JedisConnectionFactory connectionFactory() { |
12 | JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); |
13 | connectionFactory.setHostName( "localhost" ); |
14 | connectionFactory.setPort( 6379 ); |
15 | return connectionFactory; |
19 | public RedisTemplate<String, Object> redisTemplate() { |
20 | RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); |
21 | redisTemplate.setConnectionFactory(connectionFactory()); |
22 | redisTemplate.setKeySerializer( new StringRedisSerializer()); |
It performs automatic serialization/deserialization between the given objects and the underlying binary data in the Redis store. By default, it uses Java serialization for its objects.
9. Set and Get Object using Redis ValueOperations
Redis deals directly with byte arrays and doesn’t natively perform Object to byte[] translation. By default spring uses Java serialization. In the below example, we want to store Employee
object as it is and retrieve it later.
Employee:
01 | package com.javacodegeeks.spring.redis; |
03 | import java.io.Serializable; |
05 | public class Employee implements Serializable { |
06 | private static final long serialVersionUID = 1L; |
13 | public Employee(String id, String name) { |
18 | public String getId() { |
22 | public void setId(String id) { |
26 | public String getName() { |
30 | public void setName(String name) { |
34 | public Integer getAge() { |
38 | public void setAge(Integer age) { |
42 | public String toString() { |
43 | return "Employee [" + getId() + ", " + getName() + "]" ; |
Since Redis supports various operations like list operations, set operations, value operations etc, it provides sub-interfaces to deal with each use case. Since we want to set and get values, we’ll be using the ValueOperations template which we will be getting using RedisTemplate.opsForValue()
.
SpringRedisExample:
01 | package com.javacodegeeks.spring.redis; |
03 | import java.net.URISyntaxException; |
05 | import org.springframework.context.ConfigurableApplicationContext; |
06 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
07 | import org.springframework.data.redis.core.RedisTemplate; |
08 | import org.springframework.data.redis.core.ValueOperations; |
10 | public class SpringRedisExample { |
11 | public static void main(String[] args) throws URISyntaxException, Exception { |
12 | ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( |
13 | SpringRedisConfig. class ); |
15 | RedisTemplate redisTemplate = (RedisTemplate) ctx.getBean( "redisTemplate" ); |
16 | ValueOperations values = redisTemplate.opsForValue(); |
17 | values.set( "joe" , new Employee( "01" , "Joe" )); |
19 | System.out.println( "Employee added: " + values.get( "joe" )); |
Output:
1 | Jan 06, 2016 11:10:01 AM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh |
2 | INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 11:10:01 IST 2016]; root of context hierarchy |
3 | Employee added: Employee [01, Joe] |
4 | Jan 06, 2016 11:10:01 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose |
5 | INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 11:10:01 IST 2016]; root of context hierarchy |
10. StringRedisTemplate Example
If you’re going to be dealing largely with Strings, the it is better to use the specific template class StringRedisTemplate
.
Let’s modify the config class. Add strRedisTemplate()
to it to return StringRedisTemplate
object.
SpringRedisConfig:
01 | package com.javacodegeeks.spring.redis; |
03 | import org.springframework.context.annotation.Bean; |
04 | import org.springframework.context.annotation.Configuration; |
05 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; |
06 | import org.springframework.data.redis.core.RedisTemplate; |
07 | import org.springframework.data.redis.core.StringRedisTemplate; |
08 | import org.springframework.data.redis.serializer.StringRedisSerializer; |
11 | public class SpringRedisConfig { |
13 | public JedisConnectionFactory connectionFactory() { |
14 | JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); |
15 | connectionFactory.setHostName( "localhost" ); |
16 | connectionFactory.setPort( 6379 ); |
17 | return connectionFactory; |
21 | public RedisTemplate redisTemplate() { |
22 | RedisTemplate redisTemplate = new RedisTemplate(); |
23 | redisTemplate.setKeySerializer( new StringRedisSerializer()); |
24 | redisTemplate.setConnectionFactory(connectionFactory()); |
29 | public StringRedisTemplate strRedisTemplate() { |
30 | StringRedisTemplate redisTemplate = new StringRedisTemplate(); |
31 | redisTemplate.setConnectionFactory(connectionFactory()); |
SpringStringRedisExample:
01 | package com.javacodegeeks.spring.redis; |
03 | import java.net.URISyntaxException; |
05 | import org.springframework.context.ConfigurableApplicationContext; |
06 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
07 | import org.springframework.data.redis.core.StringRedisTemplate; |
08 | import org.springframework.data.redis.core.ValueOperations; |
10 | public class SpringStringRedisExample { |
11 | public static void main(String[] args) throws URISyntaxException, Exception { |
12 | ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( |
13 | SpringRedisConfig. class ); |
15 | StringRedisTemplate redisTemplate = (StringRedisTemplate) ctx.getBean( "strRedisTemplate" ); |
16 | ValueOperations values = redisTemplate.opsForValue(); |
17 | values.set( "01" , "Joe" ); |
18 | values.set( "02" , "John" ); |
20 | System.out.println( "Employee added: " + values.get( "01" )); |
21 | System.out.println( "Employee added: " + values.get( "02" )); |
Output:
1 | Jan 06, 2016 11:21:22 AM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh |
2 | INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 11:21:22 IST 2016]; root of context hierarchy |
5 | Jan 06, 2016 11:21:23 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose |
6 | INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 11:21:22 IST 2016]; root of context hierarchy |
11. Redis Hash Operations Example
In this example, we will use the Redis hash operations to store a map of attributes against a hash key. These attributes might be properties of a POJO class. This way we can store retrieves related properties with ease. CallRedisTemplate.opsForHash()
to get the hash operations object.
SpringRedisHashExample:
01 | package com.javacodegeeks.spring.redis; |
03 | import java.net.URISyntaxException; |
04 | import java.util.HashMap; |
07 | import org.springframework.context.ConfigurableApplicationContext; |
08 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
09 | import org.springframework.data.redis.core.HashOperations; |
10 | import org.springframework.data.redis.core.StringRedisTemplate; |
12 | public class SpringRedisHashExample { |
13 | public static void main(String[] args) throws URISyntaxException, Exception { |
14 | ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( |
15 | SpringRedisConfig. class ); |
17 | StringRedisTemplate redisTemplate = (StringRedisTemplate) ctx.getBean( "strRedisTemplate" ); |
18 | HashOperations<String, String, String> hash = redisTemplate.opsForHash(); |
19 | String empJoeKey = "emp:joe" ; |
20 | String empJohnKey = "emp:john" ; |
22 | Map<String, String> empJoeMap = new HashMap<>(); |
23 | empJoeMap.put( "name" , "Joe" ); |
24 | empJoeMap.put( "age" , "32" ); |
25 | empJoeMap.put( "id" , "01" ); |
27 | Map<String, String> empJohnMap = new HashMap<>(); |
28 | empJohnMap.put( "name" , "John" ); |
29 | empJohnMap.put( "age" , "42" ); |
30 | empJohnMap.put( "id" , "02" ); |
32 | hash.putAll(empJoeKey, empJoeMap); |
33 | hash.putAll(empJohnKey, empJohnMap); |
35 | System.out.println( "Get emp joe details: " + hash.entries(empJoeKey)); |
36 | System.out.println( "Get emp john details: " + hash.entries(empJohnKey)); |
Output:
1 | Jan 06, 2016 12:24:03 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh |
2 | INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 12:24:03 IST 2016]; root of context hierarchy |
3 | Get emp joe details: { id =01, age=32, name=Joe} |
4 | Get emp john details: {age=42, name=John, id =02} |
5 | Jan 06, 2016 12:24:03 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose |
6 | INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 12:24:03 IST 2016]; root of context hierarchy |
12. Redis AtomicLong Example
In case of distributed application, there may be scenarios where we need a unique number which is unique across the applications in cluster. Spring Data Redis uses the value operations internally to manage the atomic numbers likeAtomicInteger
, AtomicLong
and backs the current by a Redis instance. This way we can always generate a unique number irrespective of the JVM. In thebelow example, we use instance of RedisAtomicLong
to get the current long number set against a key and increment it atomically.
SpringRedisAtomicLongExample:
01 | package com.javacodegeeks.spring.redis; |
03 | import java.net.URISyntaxException; |
05 | import org.springframework.context.ConfigurableApplicationContext; |
06 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
07 | import org.springframework.data.redis.connection.RedisConnectionFactory; |
08 | import org.springframework.data.redis.support.atomic.RedisAtomicLong; |
10 | public class SpringRedisAtomicLongExample { |
11 | public static void main(String[] args) throws URISyntaxException, Exception { |
12 | ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( |
13 | SpringRedisConfig. class ); |
15 | RedisConnectionFactory connectionFactory = (RedisConnectionFactory) ctx.getBean( "connectionFactory" ); |
16 | RedisAtomicLong uniqueNbr = |
17 | new RedisAtomicLong( "RedisUniqueNbr" , connectionFactory, 0 ); |
18 | System.out.println( "Redis Atomic Long: " + uniqueNbr.incrementAndGet()); |
Output:
1 | Jan 06, 2016 2:21:50 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh |
2 | INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@45c8e616: startup date [Wed Jan 06 14:21:50 IST 2016]; root of context hierarchy |
4 | Jan 06, 2016 2:22:27 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose |
5 | INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@45c8e616: startup date [Wed Jan 06 14:21:50 IST 2016]; root of context hierarchy |
13. Download the source code
This was an example about Spring Data Redis.
출처: http://examples.javacodegeeks.com/enterprise-java/spring/spring-data-redis-example-2/