SpringBoot整合Redis步骤,手把手教你一步步实现
wptr33 2025-07-19 23:05 12 浏览
前言:
关于Spring的知识点总结了一个思维导图分享给大家:
一、Maven依赖
(1)本文所采用的SpringBoot的版本如下:
1 <parent> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-parent</artifactId> 4 <version>2.0.2.RELEASE</version> 5 <relativePath/> <!-- lookup parent from repository --> 6 </parent>
(2)加入Redis相关依赖
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency>
二、application.properties中加入redis相关配置
1 #Redis数据库索引(默认为0) 2 spring.redis.database=0 3 #Redis服务器地址 4 spring.redis.host=192.168.0.24 5 #Redis服务器连接端口 6 spring.redis.port=6379 7 #Redis服务器连接密码(默认为空) 8 spring.redis.password= 9 #连接池最大连接数(使用负值表示没有限制) 10
spring.redis.pool.max-active=200 11 #连接池最大阻塞等待时间(使用负值表示没有限制) 12
spring.redis.pool.max-wait=-1 13 #连接池中的最大空闲连接 14
spring.redis.pool.max-idle=10 15 #连接池中的最小空闲连接 16
spring.redis.pool.min-idle=0 17 #连接超时时间(毫秒) 18 spring.redis.timeout=1000
三、写一个redis配置类
(1)聊聊RedisTemplate的自动配置
其实现在就可以在代码中注入RedisTemplate,为啥可以直接注入呢?先看下源码吧。
下图为RedisAutoConfiguration类中的截图,为了防止图片失效,代码也贴上。
代码:
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
通过源码可以看出,SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式。 看到这个@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。
(2)既然自动配置不好用,就重新配置一个RedisTemplate
代码如下:
package com.zxy.demo.redis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* redis配置类
* @author ZENG.XIAO.YAN
* @date 2018年6月6日
*
*/
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
四、写一个Redis工具类
直接用RedisTemplate操作Redis,需要很多行代码,因此直接封装好一个RedisUtils,这样写代码更方便点。这个RedisUtils交给Spring容器实例化,使用时直接注解注入。
工具类代码如下:
package com.zxy.demo.redis;
2
3
import java.util.List;
4
import java.util.Map;
5
import java.util.Set;
6
import java.util.concurrent.TimeUnit;
7
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.data.redis.core.RedisTemplate;
10
import org.springframework.stereotype.Component;
11
import org.springframework.util.CollectionUtils;
12
13
/**
14
* Redis工具类
15
* @author ZENG.XIAO.YAN
16
* @date 2018年6月7日
17
*/
18
@Component
19
public final class RedisUtil {
20
21
@Autowired
22
private RedisTemplate<String, Object> redisTemplate;
23
24
// =============================common============================
25
/**
26
* 指定缓存失效时间
27
* @param key 键
28
* @param time 时间(秒)
29
* @return
30
*/
31
public boolean expire(String key, long time) {
32
try {
33
if (time > 0) {
34
redisTemplate.expire(key, time, TimeUnit.SECONDS);
35
}
36
return true;
37
} catch (Exception e) {
38
e.printStackTrace();
39
return false;
40
}
41
}
42
43
/**
44
* 根据key 获取过期时间
45
* @param key 键 不能为null
46
* @return 时间(秒) 返回0代表为永久有效
47
*/
48
public long getExpire(String key) {
49
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
50
}
51
52
/**
53
* 判断key是否存在
54
* @param key 键
55
* @return true 存在 false不存在
56
*/
57
public boolean hasKey(String key) {
58
try {
59
return redisTemplate.hasKey(key);
60
} catch (Exception e) {
61
e.printStackTrace();
62
return false;
63
}
64
}
65
66
/**
67
* 删除缓存
68
* @param key 可以传一个值 或多个
69
*/
70
@SuppressWarnings("unchecked")
71
public void del(String... key) {
72
if (key != null && key.length > 0) {
73
if (key.length == 1) {
74
redisTemplate.delete(key[0]);
75
} else {
76
redisTemplate.delete(CollectionUtils.arrayToList(key));
77
}
78
}
79
}
80
81
// ============================String=============================
82
/**
83
* 普通缓存获取
84
* @param key 键
85
* @return 值
86
*/
87
public Object get(String key) {
88
return key == null ? null : redisTemplate.opsForValue().get(key);
89
}
90
91
/**
92
* 普通缓存放入
93
* @param key 键
94
* @param value 值
95
* @return true成功 false失败
96
*/
97
public boolean set(String key, Object value) {
98
try {
99
redisTemplate.opsForValue().set(key, value);
100
return true;
101
} catch (Exception e) {
102
e.printStackTrace();
103
return false;
104
}
105
106
}
107
108
/**
109
* 普通缓存放入并设置时间
110
* @param key 键
111
* @param value 值
112
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
113
* @return true成功 false 失败
114
*/
115
public boolean set(String key, Object value, long time) {
116
try {
117
if (time > 0) {
118
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
119
} else {
120
set(key, value);
121
}
122
return true;
123
} catch (Exception e) {
124
e.printStackTrace();
125
return false;
126
}
127
}
128
129
/**
130
* 递增
131
* @param key 键
132
* @param delta 要增加几(大于0)
133
* @return
134
*/
135
public long incr(String key, long delta) {
136
if (delta < 0) {
137
throw new RuntimeException("递增因子必须大于0");
138
}
139
return redisTemplate.opsForValue().increment(key, delta);
140
}
141
142
/**
143
* 递减
144
* @param key 键
145
* @param delta 要减少几(小于0)
146
* @return
147
*/
148
public long decr(String key, long delta) {
149
if (delta < 0) {
150
throw new RuntimeException("递减因子必须大于0");
151
}
152
return redisTemplate.opsForValue().increment(key, -delta);
153
}
154
155
// ================================Map=================================
156
/**
157
* HashGet
158
* @param key 键 不能为null
159
* @param item 项 不能为null
160
* @return 值
161
*/
162
public Object hget(String key, String item) {
163
return redisTemplate.opsForHash().get(key, item);
164
}
165
166
/**
167
* 获取hashKey对应的所有键值
168
* @param key 键
169
* @return 对应的多个键值
170
*/
171
public Map<Object, Object> hmget(String key) {
172
return redisTemplate.opsForHash().entries(key);
173
}
174
175
/**
176
* HashSet
177
* @param key 键
178
* @param map 对应多个键值
179
* @return true 成功 false 失败
180
*/
181
public boolean hmset(String key, Map<String, Object> map) {
182
try {
183
redisTemplate.opsForHash().putAll(key, map);
184
return true;
185
} catch (Exception e) {
186
e.printStackTrace();
187
return false;
188
}
189
}
190
191
/**
192
* HashSet 并设置时间
193
* @param key 键
194
* @param map 对应多个键值
195
* @param time 时间(秒)
196
* @return true成功 false失败
197
*/
198
public boolean hmset(String key, Map<String, Object> map, long time) {
199
try {
200
redisTemplate.opsForHash().putAll(key, map);
201
if (time > 0) {
202
expire(key, time);
203
}
204
return true;
205
} catch (Exception e) {
206
e.printStackTrace();
207
return false;
208
}
209
}
210
211
/**
212
* 向一张hash表中放入数据,如果不存在将创建
213
* @param key 键
214
* @param item 项
215
* @param value 值
216
* @return true 成功 false失败
217
*/
218
public boolean hset(String key, String item, Object value) {
219
try {
220
redisTemplate.opsForHash().put(key, item, value);
221
return true;
222
} catch (Exception e) {
223
e.printStackTrace();
224
return false;
225
}
226
}
227
228
/**
229
* 向一张hash表中放入数据,如果不存在将创建
230
* @param key 键
231
* @param item 项
232
* @param value 值
233
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
234
* @return true 成功 false失败
235
*/
236
public boolean hset(String key, String item, Object value, long time) {
237
try {
238
redisTemplate.opsForHash().put(key, item, value);
239
if (time > 0) {
240
expire(key, time);
241
}
242
return true;
243
} catch (Exception e) {
244
e.printStackTrace();
245
return false;
246
}
247
}
248
249
/**
250
* 删除hash表中的值
251
* @param key 键 不能为null
252
* @param item 项 可以使多个 不能为null
253
*/
254
public void hdel(String key, Object... item) {
255
redisTemplate.opsForHash().delete(key, item);
256
}
257
258
/**
259
* 判断hash表中是否有该项的值
260
* @param key 键 不能为null
261
* @param item 项 不能为null
262
* @return true 存在 false不存在
263
*/
264
public boolean hHasKey(String key, String item) {
265
return redisTemplate.opsForHash().hasKey(key, item);
266
}
267
268
/**
269
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
270
* @param key 键
271
* @param item 项
272
* @param by 要增加几(大于0)
273
* @return
274
*/
275
public double hincr(String key, String item, double by) {
276
return redisTemplate.opsForHash().increment(key, item, by);
277
}
278
279
/**
280
* hash递减
281
* @param key 键
282
* @param item 项
283
* @param by 要减少记(小于0)
284
* @return
285
*/
286
public double hdecr(String key, String item, double by) {
287
return redisTemplate.opsForHash().increment(key, item, -by);
288
}
289
290
// ============================set=============================
291
/**
292
* 根据key获取Set中的所有值
293
* @param key 键
294
* @return
295
*/
296
public Set<Object> sGet(String key) {
297
try {
298
return redisTemplate.opsForSet().members(key);
299
} catch (Exception e) {
300
e.printStackTrace();
301
return null;
302
}
303
}
304
305
/**
306
* 根据value从一个set中查询,是否存在
307
* @param key 键
308
* @param value 值
309
* @return true 存在 false不存在
310
*/
311
public boolean sHasKey(String key, Object value) {
312
try {
313
return redisTemplate.opsForSet().isMember(key, value);
314
} catch (Exception e) {
315
e.printStackTrace();
316
return false;
317
}
318
}
319
320
/**
321
* 将数据放入set缓存
322
* @param key 键
323
* @param values 值 可以是多个
324
* @return 成功个数
325
*/
326
public long sSet(String key, Object... values) {
327
try {
328
return redisTemplate.opsForSet().add(key, values);
329
} catch (Exception e) {
330
e.printStackTrace();
331
return 0;
332
}
333
}
334
335
/**
336
* 将set数据放入缓存
337
* @param key 键
338
* @param time 时间(秒)
339
* @param values 值 可以是多个
340
* @return 成功个数
341
*/
342
public long sSetAndTime(String key, long time, Object... values) {
343
try {
344
Long count = redisTemplate.opsForSet().add(key, values);
345
if (time > 0)
346
expire(key, time);
347
return count;
348
} catch (Exception e) {
349
e.printStackTrace();
350
return 0;
351
}
352
}
353
354
/**
355
* 获取set缓存的长度
356
* @param key 键
357
* @return
358
*/
359
public long sGetSetSize(String key) {
360
try {
361
return redisTemplate.opsForSet().size(key);
362
} catch (Exception e) {
363
e.printStackTrace();
364
return 0;
365
}
366
}
367
368
/**
369
* 移除值为value的
370
* @param key 键
371
* @param values 值 可以是多个
372
* @return 移除的个数
373
*/
374
public long setRemove(String key, Object... values) {
375
try {
376
Long count = redisTemplate.opsForSet().remove(key, values);
377
return count;
378
} catch (Exception e) {
379
e.printStackTrace();
380
return 0;
381
}
382
}
383
// ===============================list=================================
384
385
/**
386
* 获取list缓存的内容
387
* @param key 键
388
* @param start 开始
389
* @param end 结束 0 到 -1代表所有值
390
* @return
391
*/
392
public List<Object> lGet(String key, long start, long end) {
393
try {
394
return redisTemplate.opsForList().range(key, start, end);
395
} catch (Exception e) {
396
e.printStackTrace();
397
return null;
398
}
399
}
400
401
/**
402
* 获取list缓存的长度
403
* @param key 键
404
* @return
405
*/
406
public long lGetListSize(String key) {
407
try {
408
return redisTemplate.opsForList().size(key);
409
} catch (Exception e) {
410
e.printStackTrace();
411
return 0;
412
}
413
}
414
415
/**
416
* 通过索引 获取list中的值
417
* @param key 键
418
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
419
* @return
420
*/
421
public Object lGetIndex(String key, long index) {
422
try {
423
return redisTemplate.opsForList().index(key, index);
424
} catch (Exception e) {
425
e.printStackTrace();
426
return null;
427
}
428
}
429
430
/**
431
* 将list放入缓存
432
* @param key 键
433
* @param value 值
434
* @param time 时间(秒)
435
* @return
436
*/
437
public boolean lSet(String key, Object value) {
438
try {
439
redisTemplate.opsForList().rightPush(key, value);
440
return true;
441
} catch (Exception e) {
442
e.printStackTrace();
443
return false;
444
}
445
}
446
447
/**
448
* 将list放入缓存
449
* @param key 键
450
* @param value 值
451
* @param time 时间(秒)
452
* @return
453
*/
454
public boolean lSet(String key, Object value, long time) {
455
try {
456
redisTemplate.opsForList().rightPush(key, value);
457
if (time > 0)
458
expire(key, time);
459
return true;
460
} catch (Exception e) {
461
e.printStackTrace();
462
return false;
463
}
464
}
465
466
/**
467
* 将list放入缓存
468
* @param key 键
469
* @param value 值
470
* @param time 时间(秒)
471
* @return
472
*/
473
public boolean lSet(String key, List<Object> value) {
474
try {
475
redisTemplate.opsForList().rightPushAll(key, value);
476
return true;
477
} catch (Exception e) {
478
e.printStackTrace();
479
return false;
480
}
481
}
482
483
/**
484
* 将list放入缓存
485
*
486
* @param key 键
487
* @param value 值
488
* @param time 时间(秒)
489
* @return
490
*/
491
public boolean lSet(String key, List<Object> value, long time) {
492
try {
493
redisTemplate.opsForList().rightPushAll(key, value);
494
if (time > 0)
495
expire(key, time);
496
return true;
497
} catch (Exception e) {
498
e.printStackTrace();
499
return false;
500
}
501
}
502
503
/**
504
* 根据索引修改list中的某条数据
505
* @param key 键
506
* @param index 索引
507
* @param value 值
508
* @return
509
*/
510
public boolean lUpdateIndex(String key, long index, Object value) {
511
try {
512
redisTemplate.opsForList().set(key, index, value);
513
return true;
514
} catch (Exception e) {
515
e.printStackTrace();
516
return false;
517
}
518
}
519
520
/**
521
* 移除N个值为value
522
* @param key 键
523
* @param count 移除多少个
524
* @param value 值
525
* @return 移除的个数
526
*/
527
public long lRemove(String key, long count, Object value) {
528
try {
529
Long remove = redisTemplate.opsForList().remove(key, count, value);
530
return remove;
531
} catch (Exception e) {
532
e.printStackTrace();
533
return 0;
534
}
535
}
536
}
最后
我这边整理了一份:Spring相关资料文档、Spring全家桶系列,Java的系统化资料,(包括Java核心知识点、面试专题和20年最新的互联网真题、电子书等)有需要的朋友可以私信回复【面试题】即可获取。
相关推荐
- MySQL进阶五之自动读写分离mysql-proxy
-
自动读写分离目前,大量现网用户的业务场景中存在读多写少、业务负载无法预测等情况,在有大量读请求的应用场景下,单个实例可能无法承受读取压力,甚至会对业务产生影响。为了实现读取能力的弹性扩展,分担数据库压...
- 3分钟短文 | Laravel SQL筛选两个日期之间的记录,怎么写?
-
引言今天说一个细分的需求,在模型中,或者使用laravel提供的EloquentORM功能,构造查询语句时,返回位于两个指定的日期之间的条目。应该怎么写?本文通过几个例子,为大家梳理一下。学习时...
- 一文由浅入深带你完全掌握MySQL的锁机制原理与应用
-
本文将跟大家聊聊InnoDB的锁。本文比较长,包括一条SQL是如何加锁的,一些加锁规则、如何分析和解决死锁问题等内容,建议耐心读完,肯定对大家有帮助的。为什么需要加锁呢?...
- 验证Mysql中联合索引的最左匹配原则
-
后端面试中一定是必问mysql的,在以往的面试中好几个面试官都反馈我Mysql基础不行,今天来着重复习一下自己的弱点知识。在Mysql调优中索引优化又是非常重要的方法,不管公司的大小只要后端项目中用到...
- MySQL索引解析(联合索引/最左前缀/覆盖索引/索引下推)
-
目录1.索引基础...
- 你会看 MySQL 的执行计划(EXPLAIN)吗?
-
SQL执行太慢怎么办?我们通常会使用EXPLAIN命令来查看SQL的执行计划,然后根据执行计划找出问题所在并进行优化。用法简介...
- MySQL 从入门到精通(四)之索引结构
-
索引概述索引(index),是帮助MySQL高效获取数据的数据结构(有序),在数据之外,数据库系统还维护者满足特定查询算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构...
- mysql总结——面试中最常问到的知识点
-
mysql作为开源数据库中的榜一大哥,一直是面试官们考察的重中之重。今天,我们来总结一下mysql的知识点,供大家复习参照,看完这些知识点,再加上一些边角细节,基本上能够应付大多mysql相关面试了(...
- mysql总结——面试中最常问到的知识点(2)
-
首先我们回顾一下上篇内容,主要复习了索引,事务,锁,以及SQL优化的工具。本篇文章接着写后面的内容。性能优化索引优化,SQL中索引的相关优化主要有以下几个方面:最好是全匹配。如果是联合索引的话,遵循最...
- MySQL基础全知全解!超详细无废话!轻松上手~
-
本期内容提醒:全篇2300+字,篇幅较长,可搭配饭菜一同“食”用,全篇无废话(除了这句),干货满满,可收藏供后期反复观看。注:MySQL中语法不区分大小写,本篇中...
- 深入剖析 MySQL 中的锁机制原理_mysql 锁详解
-
在互联网软件开发领域,MySQL作为一款广泛应用的关系型数据库管理系统,其锁机制在保障数据一致性和实现并发控制方面扮演着举足轻重的角色。对于互联网软件开发人员而言,深入理解MySQL的锁机制原理...
- Java 与 MySQL 性能优化:MySQL分区表设计与性能优化全解析
-
引言在数据库管理领域,随着数据量的不断增长,如何高效地管理和操作数据成为了一个关键问题。MySQL分区表作为一种有效的数据管理技术,能够将大型表划分为多个更小、更易管理的分区,从而提升数据库的性能和可...
- MySQL基础篇:DQL数据查询操作_mysql 查
-
一、基础查询DQL基础查询语法SELECT字段列表FROM表名列表WHERE条件列表GROUPBY分组字段列表HAVING分组后条件列表ORDERBY排序字段列表LIMIT...
- MySql:索引的基本使用_mysql索引的使用和原理
-
一、索引基础概念1.什么是索引?索引是数据库表的特殊数据结构(通常是B+树),用于...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
程序员的开源月刊《HelloGitHub》第 71 期
-
详细介绍一下Redis的Watch机制,可以利用Watch机制来做什么?
-
假如有100W个用户抢一张票,除了负载均衡办法,怎么支持高并发?
-
Java面试必考问题:什么是乐观锁与悲观锁
-
如何将AI助手接入微信(打开ai手机助手)
-
redission YYDS spring boot redission 使用
-
SparkSQL——DataFrame的创建与使用
-
一文带你了解Redis与Memcached? redis与memcached的区别
-
如何利用Redis进行事务处理呢? 如何利用redis进行事务处理呢英文
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)