Springboot基于RedisTemplate对Redis的封装

@[toc]

一. 概述

1.1 什么是RedisTemplate?

RedisTemplate是对Redis的封装,它能够简化与Redis进行数据交互的细节,提升功能效率和降低使用难度。

1.2 使用方式:

引入Spring-Redis的启动器,在yml等配置文件中配置了相关的Redis地址等信息即可使用。@Autowired引入RedisTemplate即可使用。

1.3 为什么还要封装Redis呢?

  • 在使用Redis的过程中,它的RedisTemplate会将数据转为二进制,我们在使用桌面版Redis客户端的时候(RedisDesktopManager)只能看到二进制看不到人容易识别的名称。
  • 封装后可以进行统一设置,统一管理,更方便使用。
  • 使用多级目录易于使用。

二. 图示:

2.1 使用RedisTemplate的set方法存储的数据:

可以看出来,RedisTemplate不易于读取;我们封装后有文件夹包裹,更易于使用;

三. 示例代码(SpringBoot+SpringCloud环境)

3.1 yml配置文件图示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
spring:
redis:
database: 10 # Redis数据库索引(默认为0)
host: localhost # Redis服务器地址
port: 6379 # Redis服务器连接端口
password: # Redis服务器连接密码(默认为空)
expire:
headerExpire: #重点.....key不能带有特殊字符,必须符合变量的定意规范(字母,下划线,数字)
[SYS_VERIFYIMAGE]: 600 # 10分钟
pool:
max-active: 600 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 300 # 连接池中的最大空闲连接
max-wait: 2000 # 连接池最大阻塞等待时间(使用负值表示没有限制)
min-idle: 5 # 连接池中的最小空闲连接
timeout: 0 # 连接超时时间(毫秒)

3.2 目录结构以及文件名:

  1. 图示:

  2. 文件名: RedisConfig、RedisExpireConfig、RedisService、RedisConstans

3.3 RedisConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import com.cdmtc.redis.RedisService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
*
* - @create_by: zhanglei - @craete_time 2019/7/16
*/
@Configuration
public class RedisConfig {
/**
* - 初始化redis header对应的过期时间 - @return
*/
@Bean
public RedisExpireConfig redisExpireConfig() {
return new RedisExpireConfig();
}

@Bean
public RedisService redisService(StringRedisTemplate stringRedisTemplate) {
return new RedisService(stringRedisTemplate);
}
}

3.4 RedisExpireConfig

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
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@ConfigurationProperties(prefix = "spring.redis.expire")
public class RedisExpireConfig {
/**
* - redis中header对应的过期时间
*/
private Map<String, Long> headerExpire;

public Map<String, Long> getHeaderExpire() {
return headerExpire;
}

public void setHeaderExpire(Map<String, Long> headerExpire) {
this.headerExpire = headerExpire;
}

/**
* - 获取对应header设置的过期时间 - - @param header - @return
*/
public long getExpire4Header(String header) {
if (!CollectionUtils.isEmpty(headerExpire)) {
Long result = headerExpire.get("[" + header + "]");
if (null == result) {
result = 0L;
}
return result;
}
return 0L;
}
}

3.5 RedisService.java

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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import com.cdmtc.redis.config.RedisExpireConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("unchecked")
public class RedisService {
private Logger logger = LoggerFactory.getLogger(RedisService.class);
@SuppressWarnings("rawtypes")
private RedisTemplate template;
@SuppressWarnings({ "rawtypes" })
private ListOperations listOpe;
@SuppressWarnings("rawtypes")
private ValueOperations valueOpe;
@SuppressWarnings("rawtypes")
private HashOperations hashOpe;
@SuppressWarnings("rawtypes")
private ZSetOperations zsetOpe;
@SuppressWarnings("rawtypes")
private SetOperations setOpe;
@Autowired
private RedisExpireConfig expireConfig;

@SuppressWarnings("rawtypes")
public RedisService(RedisTemplate template) {
this.template = template;
listOpe = template.opsForList();
valueOpe = template.opsForValue();
hashOpe = template.opsForHash();
zsetOpe = template.opsForZSet();
setOpe = template.opsForSet();
this.template = template;
}

private String getKey(String head, String key) {
return head + ":" + key;
}

public String get(String head, String key) {
return (String) valueOpe.get(getKey(head, key));
}

public void set(String head, String key, String value) {
valueOpe.set(getKey(head, key), value);
// 设置过期时间
expire(head, key);
}

/**
* - 以配置文件为准,为reids设置对应的过期时间 - - @param head - @param key - @return
*/
private boolean expire(String head, String key) {
long times = expireConfig.getExpire4Header(head);
if (times > 0) {
try {
return expire(head, key, times, TimeUnit.SECONDS);
} catch (Exception e) {
logger.warn("过期时间设置失败{head:" + head + ",key:" + key + "}。");
}
}
return false;
}

/**
* - 以传入的时间为准,设置相应的过期时间 - - @param head - @param key - @param timeout - @param
* unit - @return
*/
public boolean expire(String head, String key, long timeout, TimeUnit unit) {
return template.expire(getKey(head, key), timeout, unit);
}

public boolean zadd(String head, String key, String member, double score) {
boolean result = zsetOpe.add(getKey(head, key), member, score);
expire(head, key);
return result;
}

/**
* - 按分数从小到大获取指定数量 - - @param head - @param key - @param start - @param end
* - @return
*/
public Set<String> rang(String head, String key, long start, long end) {
return zsetOpe.range(getKey(head, key), start, end);
}

/**
* - 按分数从大到小获取指定数量 - - @param head - @param key - @param start - @param end
* - @return
*/
public Set<String> reverseRange(String head, String key, long start, long end) {
return zsetOpe.reverseRange(getKey(head, key), start, end);
}

/**
* - 获取指定key下成员的分数 - - @param head - @param key - @param member - @return
*/
public double score(String head, String key, String member) {
return zsetOpe.score(getKey(head, key), member);
}

/**
* - 获取排名--score低-->高 - - @param head - @param key - @param member - @return
*/
public long rank(String head, String key, String member) {
return zsetOpe.rank(getKey(head, key), member);
}

/**
* - 获取排名--score高-->低 - - @param head - @param key - @param member - @return
*/
public long reverseRank(String head, String key, String member) {
return zsetOpe.reverseRank(getKey(head, key), member);
}

/**
* - 获取指定起始位置的排行榜信息 - - @param head - @param key - @param start - @param end
* - @return
*/
public Set<ZSetOperations.TypedTuple<String>> reverseRangeWithScores(String head, String key, long start,
long end) {
return zsetOpe.reverseRangeWithScores(getKey(head, key), start, end);
}

/**
* - 获取批量hashkey对应value对象json字符串 - - @param head - @param key - @param fields
* - @param - @param < - @return
*/
public List<String> hmget(String head, String key, Collection<?> fields) {
if (CollectionUtils.isEmpty(fields)) {
return null;
}
return hashOpe.multiGet(getKey(head, key), fields);
}

/**
* - hset 操作 - - @param head - @param key - @param field - @param value
*/
public void hset(String head, String key, String field, String value) {
hashOpe.put(getKey(head, key), field, value);
expire(head, key);
}

/**
* - 获取所有的field - - @param head - @param key - @return
*/
public Set<String> keys(String head, String key) {
return hashOpe.keys(getKey(head, key));
}

/**
* - 通过field获取value - - @param head - @param key - @param field - @return
*/
public String hget(String head, String key, String field) {
return (String) hashOpe.get(getKey(head, key), field);
}

/**
* - 获取set里对应成员 - - @param head - @param key - @param - @return
*/
public Set<String> smembers(String head, String key) {
return setOpe.members(getKey(head, key));
}

/**
* - 通过field获取value - - @param head - @param key - @param value - @return
*/
public long sadd(String head, String key, String value) {
long result = setOpe.add(getKey(head, key), value);
expire(head, key);
return result;
}

/**
* - 在value后面追加值 - - @param head - @param key - @param addString
*/
public int append(String head, String key, String addString) {
return valueOpe.append(getKey(head, key), addString);
}

/**
* - 加锁机制 true加锁成功 false加锁失败 - - @param head - @param key - @param lockValue
*/
public boolean setnx(String head, String key, String lockValue) {
boolean success = valueOpe.setIfAbsent(getKey(head, key), lockValue);
if (success) {
// 设置过期时间
expire(head, key);
}
return success;
}

/**
* - 删除KEY - - @param head - @param key
*/
public boolean delete(String head, String key) {
return template.delete(getKey(head, key));
}

public long rightPush(String head, String key, String value) {
return listOpe.rightPush(getKey(head, key), value);
}

/**
*
* - @param head - @param key - @param member - @return
*/
public Double incrementScore(String head, String key, String member, Double score) {
return zsetOpe.incrementScore(getKey(head, key), member, score);
}

/**
* - @description: - @param head - @param key - @param map - @return: void
*/
public void hmset(String head, String key, Map<? extends String, ? extends String> map) {
if (!CollectionUtils.isEmpty(map)) {
hashOpe.putAll(getKey(head, key), map);
expire(head, key);
}
}

/**
*
* - @param head - @param key - @param filed - @param value - @return
*/
public Double Hincrby(String head, String key, String filed, Double value) {
return hashOpe.increment(getKey(head, key), filed, value);
}

/**
* - 删除hash数据结构
*
* - @param head - @param key
*/
public Long hdel(String head, String key, String field) {
return hashOpe.delete(getKey(head, key), field);
}

/**
* - 判断可以是否存在 - @param head - @param key - @return
*/
public boolean hasKey(String head, String key) {
return template.hasKey(getKey(head, key));
}

}

3.6 RedisConstans

1
2
3
public class RedisConstans {
public static String SYS_VERIFYIMAGE="SYS_VERIFYIMAGE"; // webSocket 发送消息类型
}