Hello World

[펌]Spring Data Redis Example 본문

Spring/Boot(4.x)

[펌]Spring Data Redis Example

EnterKey 2016. 1. 10. 11:54
반응형

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

  1. Download Redis Release. We have downloaded the release for Windows 3.0 on 64 bit.
  2. Download the binaries, bundled as zip file and the installer MSI file.
  3. Unzip the binaries to a new directory, for example, c:\redis. Copy the installer to the same directory.
  4. Run the installer file and follow through the wizard.
  5. 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.

01C:\redis<redis-server.exe
02[5784] 06 Jan 08:46:59.903 # Warning: no config file specified, using the defaul
03t config. In order to specify a config file use redis-server.exe /path/to/redis.
04conf
05                _._
06           _.-``__ ''-._
07      _.-``    `.  `_.  ''-._           Redis 3.0.500 (00000000/0) 64 bit
08  .-`` .-```.  ```\/    _.,_ ''-._
09 (    '      ,       .-`  | `,    )     Running in standalone mode
10 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
11 |    `-._   `._    /     _.-'    |     PID: 5784
12  `-._    `-._  `-./  _.-'    _.-'
13 |`-._`-._    `-.__.-'    _.-'_.-'|
14 |    `-._`-._        _.-'_.-'    |           http://redis.io
15  `-._    `-._`-.__.-'_.-'    _.-'
16 |`-._`-._    `-.__.-'    _.-'_.-'|
17 |    `-._`-._        _.-'_.-'    |
18  `-._    `-._`-.__.-'_.-'    _.-'
19      `-._    `-.__.-'    _.-'
20          `-._        _.-'
21              `-.__.-'
22 
23[5784] 06 Jan 08:46:59.920 # Server started, Redis version 3.0.500
24[5784] 06 Jan 08:46:59.921 * The server is now ready to accept connections on po
25rt 6379

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.

  1. Go to the installed redis directory and then run redis-cli from command line.
    1C:\redis<redis-cli
    2127.0.0.1:6379<
  2. Get all the keys.
    1127.0.0.1:6379< keys *
    2(empty list or set)
    3127.0.0.1:6379>
  3. Insert a key value.
    1127.0.0.1:6379< set example spring-redis
    2OK
  4. Get all the keys.
    1127.0.0.1:6379< keys *
    21) "example"
    3127.0.0.1:6379>
  5. Let’s now get value of “example”.
    1127.0.0.1:6379< get example
    2"spring-redis"

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:

1<dependency>
2    <groupId>redis.clients</groupId>
3    <artifactId>jedis</artifactId>
4    <version>2.8.0</version>
5</dependency>

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.

  1. spring-data-redis is for the spring-redis support.
  2. spring-core and spring-context for spring bean and context support.
  3. commons-pool2 – Apache commons pool
  4. jedis – 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>
07    <dependencies>
08        <dependency>
09            <groupId>org.springframework</groupId>
10            <artifactId>spring-core</artifactId>
11            <version>4.1.5.RELEASE</version>
12        </dependency>
13        <dependency>
14            <groupId>org.springframework</groupId>
15            <artifactId>spring-context</artifactId>
16            <version>4.1.5.RELEASE</version>
17        </dependency>
18        <dependency>
19            <groupId>org.springframework.data</groupId>
20            <artifactId>spring-data-redis</artifactId>
21            <version>1.5.0.RELEASE</version>
22        </dependency>
23        <dependency>
24            <groupId>org.apache.commons</groupId>
25            <artifactId>commons-pool2</artifactId>
26            <version>2.4.2</version>
27        </dependency>
28        <dependency>
29            <groupId>redis.clients</groupId>
30            <artifactId>jedis</artifactId>
31            <version>2.8.0</version>
32        </dependency>
33 
34    </dependencies>
35</project>

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:

01package com.javacodegeeks.spring.redis;
02 
03import org.springframework.context.annotation.Bean;
04import org.springframework.context.annotation.Configuration;
05import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
06import org.springframework.data.redis.core.StringRedisTemplate;
07 
08@Configuration
09public class SpringRedisConfig {
10    @Bean
11    public JedisConnectionFactory connectionFactory() {
12        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
13        connectionFactory.setHostName("localhost");
14        connectionFactory.setPort(6379);
15        return connectionFactory;
16    }
17}

8. RedisTemplate Example

Just the way spring provides template classes, even for redis, spring provides RedisTemplate to simplify Redis data access code.

SpringRedisConfig:

01package com.javacodegeeks.spring.redis;
02 
03import org.springframework.context.annotation.Bean;
04import org.springframework.context.annotation.Configuration;
05import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
06import org.springframework.data.redis.core.RedisTemplate;
07 
08@Configuration
09public class SpringRedisConfig {
10    @Bean
11    public JedisConnectionFactory connectionFactory() {
12        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
13        connectionFactory.setHostName("localhost");
14        connectionFactory.setPort(6379);
15        return connectionFactory;
16    }
17 
18    @Bean
19    public RedisTemplate<String, Object> redisTemplate() {
20        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
21        redisTemplate.setConnectionFactory(connectionFactory());
22                redisTemplate.setKeySerializer(new StringRedisSerializer());
23        return redisTemplate;
24    }
25}

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:

01package com.javacodegeeks.spring.redis;
02 
03import java.io.Serializable;
04 
05public class Employee implements Serializable {
06    private static final long serialVersionUID = 1L;
07    private String id;
08    private String name;
09    private Integer age;
10 
11    public Employee(){}
12     
13    public Employee(String id, String name) {
14        this.id = id;
15        this.name = name;
16    }
17     
18    public String getId() {
19        return id;
20    }
21 
22    public void setId(String id) {
23        this.id = id;
24    }
25 
26    public String getName() {
27        return name;
28    }
29 
30    public void setName(String name) {
31        this.name = name;
32    }
33 
34    public Integer getAge() {
35        return age;
36    }
37 
38    public void setAge(Integer age) {
39        this.age = age;
40    }
41 
42    public String toString() {
43        return "Employee [" + getId() + ", " + getName() + "]";
44    }
45}

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:

01package com.javacodegeeks.spring.redis;
02 
03import java.net.URISyntaxException;
04 
05import org.springframework.context.ConfigurableApplicationContext;
06import org.springframework.context.annotation.AnnotationConfigApplicationContext;
07import org.springframework.data.redis.core.RedisTemplate;
08import org.springframework.data.redis.core.ValueOperations;
09 
10public class SpringRedisExample {
11    public static void main(String[] args) throws URISyntaxException, Exception {
12        ConfigurableApplicationContext ctx = newAnnotationConfigApplicationContext(
13                SpringRedisConfig.class);
14        try {          
15            RedisTemplate redisTemplate = (RedisTemplate) ctx.getBean("redisTemplate");
16            ValueOperations values = redisTemplate.opsForValue();
17            values.set("joe"new Employee("01""Joe"));
18             
19            System.out.println("Employee added: " + values.get("joe"));
20        finally {
21            ctx.close();
22        }
23    }
24}

Output:

1Jan 06, 2016 11:10:01 AM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
2INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 11:10:01 IST 2016]; root of context hierarchy
3Employee added: Employee [01, Joe]
4Jan 06, 2016 11:10:01 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
5INFO: 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:

01package com.javacodegeeks.spring.redis;
02 
03import org.springframework.context.annotation.Bean;
04import org.springframework.context.annotation.Configuration;
05import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
06import org.springframework.data.redis.core.RedisTemplate;
07import org.springframework.data.redis.core.StringRedisTemplate;
08import org.springframework.data.redis.serializer.StringRedisSerializer;
09 
10@Configuration
11public class SpringRedisConfig {
12    @Bean
13    public JedisConnectionFactory connectionFactory() {
14        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
15        connectionFactory.setHostName("localhost");
16        connectionFactory.setPort(6379);
17        return connectionFactory;
18    }
19 
20    @Bean
21    public RedisTemplate redisTemplate() {
22        RedisTemplate redisTemplate = new RedisTemplate();
23        redisTemplate.setKeySerializer(new StringRedisSerializer());
24        redisTemplate.setConnectionFactory(connectionFactory());
25        return redisTemplate;
26    }
27     
28    @Bean
29    public StringRedisTemplate strRedisTemplate() {
30        StringRedisTemplate redisTemplate = new StringRedisTemplate();
31        redisTemplate.setConnectionFactory(connectionFactory());
32        return redisTemplate;
33    }
34}

SpringStringRedisExample:

01package com.javacodegeeks.spring.redis;
02 
03import java.net.URISyntaxException;
04 
05import org.springframework.context.ConfigurableApplicationContext;
06import org.springframework.context.annotation.AnnotationConfigApplicationContext;
07import org.springframework.data.redis.core.StringRedisTemplate;
08import org.springframework.data.redis.core.ValueOperations;
09 
10public class SpringStringRedisExample {
11    public static void main(String[] args) throws URISyntaxException, Exception {
12        ConfigurableApplicationContext ctx = newAnnotationConfigApplicationContext(
13                SpringRedisConfig.class);
14        try {          
15            StringRedisTemplate redisTemplate = (StringRedisTemplate) ctx.getBean("strRedisTemplate");
16            ValueOperations values = redisTemplate.opsForValue();
17            values.set("01""Joe");
18            values.set("02""John");
19             
20            System.out.println("Employee added: " + values.get("01"));
21            System.out.println("Employee added: " + values.get("02"));
22        finally {
23            ctx.close();
24        }
25    }
26}

Output:

1Jan 06, 2016 11:21:22 AM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
2INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 11:21:22 IST 2016]; root of context hierarchy
3Employee added: Joe
4Employee added: John
5Jan 06, 2016 11:21:23 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
6INFO: 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:

01package com.javacodegeeks.spring.redis;
02 
03import java.net.URISyntaxException;
04import java.util.HashMap;
05import java.util.Map;
06 
07import org.springframework.context.ConfigurableApplicationContext;
08import org.springframework.context.annotation.AnnotationConfigApplicationContext;
09import org.springframework.data.redis.core.HashOperations;
10import org.springframework.data.redis.core.StringRedisTemplate;
11 
12public class SpringRedisHashExample {
13    public static void main(String[] args) throws URISyntaxException, Exception {
14        ConfigurableApplicationContext ctx = newAnnotationConfigApplicationContext(
15                SpringRedisConfig.class);
16        try {          
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";
21             
22            Map<String, String> empJoeMap = new HashMap<>();
23            empJoeMap.put("name""Joe");
24            empJoeMap.put("age""32");
25            empJoeMap.put("id""01");
26             
27            Map<String, String> empJohnMap = new HashMap<>();
28            empJohnMap.put("name""John");
29            empJohnMap.put("age""42");
30            empJohnMap.put("id""02");
31             
32            hash.putAll(empJoeKey, empJoeMap);
33            hash.putAll(empJohnKey, empJohnMap);   
34             
35            System.out.println("Get emp joe details: " + hash.entries(empJoeKey));
36            System.out.println("Get emp john details: " + hash.entries(empJohnKey));
37        finally {
38            ctx.close();
39        }
40    }
41}

Output:

1Jan 06, 2016 12:24:03 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
2INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Wed Jan 06 12:24:03 IST 2016]; root of context hierarchy
3Get emp joe details: {id=01, age=32, name=Joe}
4Get emp john details: {age=42, name=John, id=02}
5Jan 06, 2016 12:24:03 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
6INFO: 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 likeAtomicIntegerAtomicLong 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:

01package com.javacodegeeks.spring.redis;
02 
03import java.net.URISyntaxException;
04 
05import org.springframework.context.ConfigurableApplicationContext;
06import org.springframework.context.annotation.AnnotationConfigApplicationContext;
07import org.springframework.data.redis.connection.RedisConnectionFactory;
08import org.springframework.data.redis.support.atomic.RedisAtomicLong;
09 
10public class SpringRedisAtomicLongExample {
11    public static void main(String[] args) throws URISyntaxException, Exception {
12        ConfigurableApplicationContext ctx = newAnnotationConfigApplicationContext(
13                SpringRedisConfig.class);
14        try {          
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());
19             
20        finally {
21            ctx.close();
22        }
23    }
24}

Output:

1Jan 06, 2016 2:21:50 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
2INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@45c8e616: startup date [Wed Jan 06 14:21:50 IST 2016]; root of context hierarchy
3Redis Atomic Long: 1
4Jan 06, 2016 2:22:27 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
5INFO: 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.

Download
You can download the full source code of this example here: springRedisExample.zip

출처: http://examples.javacodegeeks.com/enterprise-java/spring/spring-data-redis-example-2/

반응형
Comments