22.springboot中使用redis

 

springboot中使用redis

1. 创建项目

创建一个SpringBoot项目

2. pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.redis.springboot</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Redis springboot demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>

3. 创建application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# redis configuration

spring:
redis:
host: 192.168.168.130
port: 6379
jedis:
pool:
max-active: 20
max-idle: 8
min-idle: 0
max-wait: 2000
# database: 1
cluster:
nodes: 192.168.168.130:7001,192.168.168.130:7002,192.168.168.130:7003,192.168.168.130:7004,192.168.168.130:7005,192.168.168.130:7006
max-redirects: 3

4. Redis自动配置类的说明: RedisAutoConfiguration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.boot.autoconfigure.data.redis;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}

@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

5. 测试StringRedisTemplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package com.redis.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


@SpringBootTest
class DemoApplicationTests {

@Autowired
private StringRedisTemplate stringRedisTemplate;

// redis connection
@Test
public void testRedisConnection() {
System.out.println(this.stringRedisTemplate);
// org.springframework.data.redis.core.StringRedisTemplate@448b808a
}

// stringRedisTemplate
@Test
public void testStringRedisTemplate() {
Set<String> keySet = stringRedisTemplate.keys("*");
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

stringRedisTemplate.multi();
stringRedisTemplate.exec();
stringRedisTemplate.watch("key");
stringRedisTemplate.unwatch();
stringRedisTemplate.discard();

stringRedisTemplate.delete("key");
stringRedisTemplate.delete("Collection<String> keys");
stringRedisTemplate.randomKey();
stringRedisTemplate.rename("oldKey","newKey");

// key的序列化方式
stringRedisTemplate.getKeySerializer();
// value的序列化方式
stringRedisTemplate.getValueSerializer();
// Hash的HashKey的序列化方式
stringRedisTemplate.getHashKeySerializer();
// Hash的HashValue的序列化方式
stringRedisTemplate.getHashValueSerializer();

System.out.println(stringRedisTemplate.getKeySerializer());
System.out.println(stringRedisTemplate.getValueSerializer());
System.out.println(stringRedisTemplate.getHashKeySerializer());
System.out.println(stringRedisTemplate.getHashValueSerializer());

// org.springframework.data.redis.serializer.StringRedisSerializer@1727e03a
// org.springframework.data.redis.serializer.StringRedisSerializer@1727e03a
// org.springframework.data.redis.serializer.StringRedisSerializer@1727e03a
// org.springframework.data.redis.serializer.StringRedisSerializer@1727e03a

}

// redis string
@Test
public void testRedisString() {
ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();

valueOperations.get("key");
valueOperations.set("key", "value");
valueOperations.setIfPresent("key", "value");
valueOperations.increment("key");
valueOperations.decrement("key");

RedisOperations<String, String> redisOperations = valueOperations.getOperations();

String name = valueOperations.get("name");
System.out.println(name);
// Kim

}

// redis list
@Test
public void testRedisList() {
ListOperations<String, String> listOperations = stringRedisTemplate.opsForList();

listOperations.leftPush("key", "value");
listOperations.leftPushAll("key", "value1", "value2", "..");
listOperations.leftPushAll("key", "Collection<String>");
listOperations.rightPush("key", "value");
listOperations.rightPushAll("key", "value1", "value2", "..");
listOperations.rightPushAll("key", "Collection<String>");
listOperations.leftPop("key");
listOperations.rightPop("key");

RedisOperations<String, String> redisOperations =listOperations.getOperations();

List<String> values = listOperations.range("letterList", 0, -1);
for (String value: values) {
System.out.println(value);
}
// a
// b
// c

}

// redis hash
@Test
public void testRedisHash() {
HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();

hashOperations.put("student", "id", "1");
Integer id = Integer.valueOf(hashOperations.get("student", "id").toString());

System.out.println(id);
// 1
}

// redis set
@Test
public void testRedisSet() {
SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();

setOperations.add("seriesNumber", "111", "222", "333", "444", "555");
Set<String> setMembers = setOperations.members("seriesNumber");

for(String member: setMembers) {
System.out.println(member);
}
/*
111
222
333
444
555
*/

}

// redis zset
@Test
public void testRedisZset() {
ZSetOperations zSetOperations = stringRedisTemplate.opsForZSet();
zSetOperations.add("priceList", "apple", 5.2);
zSetOperations.add("priceList", "cup", 20.6);
zSetOperations.add("priceList", "noodle", 5.5);

Set<DefaultTypedTuple> priceListSet = zSetOperations.rangeWithScores("priceList", 0, -1);
for (DefaultTypedTuple priceItem: priceListSet) {
System.out.println(priceItem.getValue() + ":" + priceItem.getScore());
}
// apple:5.2
// noodle:5.5
// cup:20.6
}

// redis cluster
@Test
public void testRedisCluster() {

ClusterOperations<String, String> clusterOperations = stringRedisTemplate.opsForCluster();
System.out.println(clusterOperations);
// org.springframework.data.redis.core.DefaultClusterOperations@642ee49c

RedisClusterNode masterNode = new RedisClusterNode("192.168.168.130", 7001);
Collection<RedisClusterNode> slaveNodes = clusterOperations.getSlaves(masterNode);
for (RedisClusterNode slaveNode: slaveNodes) {

System.out.println(slaveNode.getHost()); // 192.168.168.130
System.out.println(slaveNode.getPort()); // 7005
System.out.println(slaveNode.getId()); // 0e2148ede5c79e4c9a275d16aa67860a3eabec59
System.out.println(slaveNode.getName()); // null
System.out.println(slaveNode.getLinkState()); // CONNECTED
System.out.println(slaveNode.getType()); // SLAVE
System.out.println(slaveNode.getMasterId()); // 99abc1f93ec1832530f32c2040149f10fd6341b4

}

System.out.println(masterNode.getHost()); // 192.168.168.130
System.out.println(masterNode.getPort()); // 7001
System.out.println(masterNode.getId()); // null
System.out.println(masterNode.getName()); // null
System.out.println(masterNode.getLinkState()); // null
System.out.println(masterNode.getType()); // null
System.out.println(masterNode.getMasterId()); // null

clusterOperations.addSlots(RedisClusterNode);
clusterOperations.flushDb(RedisClusterNode);
clusterOperations.randomKey(RedisClusterNode);
clusterOperations.shutdown(RedisClusterNode);

}

@Test
public void myFlushDB() {
stringRedisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
redisConnection.flushDb();
redisConnection.flushAll();
return "success";
}
});
}

}

6. 测试RedisTemplate<Object, Object>

创建User类,实现Serializable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.redis.vo;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

private Integer id;
private String name;
private Date birthday;

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.example.demo;

import com.redis.vo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Date;

@SpringBootTest
class DemoApplicationTests {

// RedisTemplate<Object, Object>
@Autowired
private RedisTemplate redisTemplate;

@Test
public void testRedisTemplate() {
System.out.println(redisTemplate);
System.out.println(redisTemplate.getKeySerializer());
System.out.println(redisTemplate.getValueSerializer());
// org.springframework.data.redis.core.RedisTemplate@4dd90166
// org.springframework.data.redis.serializer.JdkSerializationRedisSerializer@52227eb2
// org.springframework.data.redis.serializer.JdkSerializationRedisSerializer@52227eb2
}

@Test
public void testJdkSerializationRedisSerializer() {
/*
设置key的序列化方式
如果不设置,RedisTemplate<Object, Object>的默认序列化方式为JdkSerializationRedisSerializer
传入的String类型的key会被当做Object类型,以JdkSerializationRedisSerializer方式进行序列化
String类型的key以JdkSerializationRedisSerializer方式进行序列化后不具有可读性
*/
redisTemplate.setKeySerializer(new StringRedisSerializer());

User user = new User();
user.setId(1);
user.setName("Tom");
user.setBirthday(new Date());

ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("user:1", user);

User userStorageInRedis = (User) valueOperations.get("user:1");
System.out.println(userStorageInRedis);
// com.redis.vo.User@261bd7b

}

@Test
public void testGenericJackson2JsonRedisSerializer() {
/*
设置key和value的序列化方式
如果不设置,RedisTemplate<Object, Object>的默认序列化方式为JdkSerializationRedisSerializer
设置value以GenericJackson2JsonRedisSerializer方式进行序列化具有更好的可读性和更小的体积
*/
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

User user = new User();
user.setId(2);
user.setName("Kim");
user.setBirthday(new Date());

ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("user:2", user);

User userStorageInRedis = (User) valueOperations.get("user:2");
System.out.println(userStorageInRedis);
// com.redis.vo.User@365afe87

}

}

将user:1保存到redis

将user:2保存到redis