1.导入Pom.xml依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <groupId>com.yc</groupId> 7 <artifactId>SpringCacheDome</artifactId> 8 <version>1.0-SNAPSHOT</version> 9 <dependencyManagement> 10 <dependencies> 11 <!--spring-boot--> 12 <dependency> 13 <groupId>org.springframework.boot</groupId> 14 <artifactId>spring-boot-dependencies</artifactId> 15 <version>2.1.3.RELEASE</version> 16 <type>pom</type> 17 <scope>import</scope> 18 </dependency> 19 </dependencies> 20 </dependencyManagement> 21 <dependencies> 22 <dependency> 23 <groupId>org.springframework.boot</groupId> 24 <artifactId>spring-boot-starter-web</artifactId> 25 </dependency> 26 <dependency> 27 <groupId>org.springframework.boot</groupId> 28 <artifactId>spring-boot-starter-cache</artifactId> 29 </dependency> 30 <!--SpringBoot 整合 Redis所需依赖以下俩个--> 31 <dependency> 32 <groupId>org.springframework.boot</groupId> 33 <artifactId>spring-boot-starter-redis</artifactId> 34 <version>1.4.0.RELEASE</version> 35 </dependency> 36 <!--数据库驱动包--> 37 <dependency> 38 <groupId>mysql</groupId> 39 <artifactId>mysql-connector-java</artifactId> 40 <version>5.0.4</version> 41 </dependency> 42 <!--数据库连接池--> 43 <dependency> 44 <groupId>com.alibaba</groupId> 45 <artifactId>druid</artifactId> 46 <version>1.0.31</version> 47 </dependency> 48 <!--spring-boot和mybatis整合--> 49 <dependency> 50 <groupId>org.mybatis.spring.boot</groupId> 51 <artifactId>mybatis-spring-boot-starter</artifactId> 52 <version>1.3.0</version> 53 </dependency> 54 </dependencies> 55 <!--由于idea编译器的原因所以在配置文件中指定存放位置--> 56 <build> 57 <resources> 58 <resource> 59 <directory>src/main/java</directory> 60 <includes> 61 <include>**/*.xml</include> 62 </includes> 63 </resource> 64 </resources> 65 </build> 66 </project>
2.配置yml
1 spring: 2 cache: 3 type: redis 4 #redis 5 redis: 6 host: 127.0.0.1 7 port: 6379 8 timeout: 10 9 password: 10 database: 0 11 12 datasource: 13 type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型 14 driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包 15 url: jdbc:mysql://localhost:3306/cloudDB01 #数据库名称 16 username: root 17 password: root 18 dbcp2: 19 min-idle: 5 #数据哭连接池的最小维持数 20 initial-size: 5 #初始化连接数 21 max-total: 5 #最大链接数 22 max-wait-millis: 200 #等待链接获取的最大超时时间 23 druid: 24 stat-view-servlet.enabled: true 25 stat-view-servlet.url-pattern: /druid/*
3.配置Redis缓存自定义类
1 @Configuration
2 @EnableCaching
3 public class CacheConfig {
4 /**读取yml文件中配置*/
5 @Value("${spring.redis.host}")
6 private String host;
7
8 @Value("${spring.redis.port}")
9 private int port;
10
11 @Value("${spring.redis.timeout}")
12 private int timeout;
13
14 @Value("${spring.redis.database}")
15 private int database;
16
17 @Bean
18 public JedisConnectionFactory jedisConnectionFactory(){
19 JedisConnectionFactory factory = new JedisConnectionFactory();
20 factory.setHostName(host);
21 factory.setPort(port);
22 factory.setTimeout(timeout);
23 factory.setDatabase(database);
24 return factory;
25 }
26 /**
27 * retemplate相关配置
28 * @param factory
29 * @return
30 */
31 @Bean
32 public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
33 RedisTemplate<String, Object> template = new RedisTemplate<>();
34 // 配置连接工厂
35 template.setConnectionFactory(factory);
36 //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
37 Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
38 ObjectMapper om = new ObjectMapper();
39 // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
40 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
41 // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
42 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
43 jacksonSeial.setObjectMapper(om);
44 // 值采用json序列化
45 template.setValueSerializer(jacksonSeial);
46 //使用StringRedisSerializer来序列化和反序列化redis的key值
47 template.setKeySerializer(new StringRedisSerializer());
48 // 设置hash key 和value序列化模式
49 template.setHashKeySerializer(new StringRedisSerializer());
50 template.setHashValueSerializer(jacksonSeial);
51 template.afterPropertiesSet();
52 return template;
53 }
54 }
4.Redis工具类 SpringBoot
1 /**
2 * redisTemplate封装
3 *
4 * @author yinxp@dist.com.cn
5 */
6 @Component
7 public class RedisUtils {
8
9 @Autowired
10 private RedisTemplate<String, Object> redisTemplate;
11
12 public RedisUtils(RedisTemplate<String, Object> redisTemplate) {
13 this.redisTemplate = redisTemplate;
14 }
15
16 /**
17 * 指定缓存失效时间
18 * @param key 键
19 * @param time 时间(秒)
20 * @return
21 */
22 public boolean expire(String key,long time){
23 try {
24 if(time>0){
25 redisTemplate.expire(key, time, TimeUnit.SECONDS);
26 }
27 return true;
28 } catch (Exception e) {
29 e.printStackTrace();
30 return false;
31 }
32 }
33
34 /**
35 * 根据key 获取过期时间
36 * @param key 键 不能为null
37 * @return 时间(秒) 返回0代表为永久有效
38 */
39 public long getExpire(String key){
40 return redisTemplate.getExpire(key,TimeUnit.SECONDS);
41 }
42
43 /**
44 * 判断key是否存在
45 * @param key 键
46 * @return true 存在 false不存在
47 */
48 public boolean hasKey(String key){
49 try {
50 return redisTemplate.hasKey(key);
51 } catch (Exception e) {
52 e.printStackTrace();
53 return false;
54 }
55 }
56
57 /**
58 * 删除缓存
59 * @param key 可以传一个值 或多个
60 */
61 @SuppressWarnings("unchecked")
62 public void del(String ... key){
63 if(key!=null&&key.length>0){
64 if(key.length==1){
65 redisTemplate.delete(key[0]);
66 }else{
67 redisTemplate.delete(CollectionUtils.arrayToList(key));
68 }
69 }
70 }
71
72 //============================String=============================
73 /**
74 * 普通缓存获取
75 * @param key 键
76 * @return 值
77 */
78 public Object get(String key){
79 return key==null?null:redisTemplate.opsForValue().get(key);
80 }
81
82 /**
83 * 普通缓存放入
84 * @param key 键
85 * @param value 值
86 * @return true成功 false失败
87 */
88 public boolean set(String key,Object value) {
89 try {
90 redisTemplate.opsForValue().set(key, value);
91 return true;
92 } catch (Exception e) {
93 e.printStackTrace();
94 return false;
95 }
96 }
97
98 /**
99 * 普通缓存放入并设置时间
100 * @param key 键
101 * @param value 值
102 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
103 * @return true成功 false 失败
104 */
105 public boolean set(String key,Object value,long time){
106 try {
107 if(time>0){
108 redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
109 }else{
110 set(key, value);
111 }
112 return true;
113 } catch (Exception e) {
114 e.printStackTrace();
115 return false;
116 }
117 }
118
119 /**
120 * 递增
121 * @param key 键
122 * @param delta 要增加几(大于0)
123 * @return
124 */
125 public long incr(String key, long delta){
126 if(delta<0){
127 throw new RuntimeException("递增因子必须大于0");
128 }
129 return redisTemplate.opsForValue().increment(key, delta);
130 }
131
132 /**
133 * 递减
134 * @param key 键
135 * @param delta 要减少几(小于0)
136 * @return
137 */
138 public long decr(String key, long delta){
139 if(delta<0){
140 throw new RuntimeException("递减因子必须大于0");
141 }
142 return redisTemplate.opsForValue().increment(key, -delta);
143 }
144
145 //================================Map=================================
146 /**
147 * HashGet
148 * @param key 键 不能为null
149 * @param item 项 不能为null
150 * @return 值
151 */
152 public Object hget(String key,String item){
153 return redisTemplate.opsForHash().get(key, item);
154 }
155
156 /**
157 * 获取hashKey对应的所有键值
158 * @param key 键
159 * @return 对应的多个键值
160 */
161 public Map<Object,Object> hmget(String key){
162 return redisTemplate.opsForHash().entries(key);
163 }
164
165 /**
166 * HashSet
167 * @param key 键
168 * @param map 对应多个键值
169 * @return true 成功 false 失败
170 */
171 public boolean hmset(String key, Map<String,Object> map){
172 try {
173 redisTemplate.opsForHash().putAll(key, map);
174 return true;
175 } catch (Exception e) {
176 e.printStackTrace();
177 return false;
178 }
179 }
180
181 /**
182 * HashSet 并设置时间
183 * @param key 键
184 * @param map 对应多个键值
185 * @param time 时间(秒)
186 * @return true成功 false失败
187 */
188 public boolean hmset(String key, Map<String,Object> map, long time){
189 try {
190 redisTemplate.opsForHash().putAll(key, map);
191 if(time>0){
192 expire(key, time);
193 }
194 return true;
195 } catch (Exception e) {
196 e.printStackTrace();
197 return false;
198 }
199 }
200
201 /**
202 * 向一张hash表中放入数据,如果不存在将创建
203 * @param key 键
204 * @param item 项
205 * @param value 值
206 * @return true 成功 false失败
207 */
208 public boolean hset(String key,String item,Object value) {
209 try {
210 redisTemplate.opsForHash().put(key, item, value);
211 return true;
212 } catch (Exception e) {
213 e.printStackTrace();
214 return false;
215 }
216 }
217
218 /**
219 * 向一张hash表中放入数据,如果不存在将创建
220 * @param key 键
221 * @param item 项
222 * @param value 值
223 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
224 * @return true 成功 false失败
225 */
226 public boolean hset(String key,String item,Object value,long time) {
227 try {
228 redisTemplate.opsForHash().put(key, item, value);
229 if(time>0){
230 expire(key, time);
231 }
232 return true;
233 } catch (Exception e) {
234 e.printStackTrace();
235 return false;
236 }
237 }
238
239 /**
240 * 删除hash表中的值
241 * @param key 键 不能为null
242 * @param item 项 可以使多个 不能为null
243 */
244 public void hdel(String key, Object... item){
245 redisTemplate.opsForHash().delete(key,item);
246 }
247
248 /**
249 * 判断hash表中是否有该项的值
250 * @param key 键 不能为null
251 * @param item 项 不能为null
252 * @return true 存在 false不存在
253 */
254 public boolean hHasKey(String key, String item){
255 return redisTemplate.opsForHash().hasKey(key, item);
256 }
257
258 /**
259 * hash递增 如果不存在,就会创建一个 并把新增后的值返回
260 * @param key 键
261 * @param item 项
262 * @param by 要增加几(大于0)
263 * @return
264 */
265 public double hincr(String key, String item,double by){
266 return redisTemplate.opsForHash().increment(key, item, by);
267 }
268
269 /**
270 * hash递减
271 * @param key 键
272 * @param item 项
273 * @param by 要减少记(小于0)
274 * @return
275 */
276 public double hdecr(String key, String item,double by){
277 return redisTemplate.opsForHash().increment(key, item,-by);
278 }
279
280 //============================set=============================
281 /**
282 * 根据key获取Set中的所有值
283 * @param key 键
284 * @return
285 */
286 public Set<Object> sGet(String key){
287 try {
288 return redisTemplate.opsForSet().members(key);
289 } catch (Exception e) {
290 e.printStackTrace();
291 return null;
292 }
293 }
294
295 /**
296 * 根据value从一个set中查询,是否存在
297 * @param key 键
298 * @param value 值
299 * @return true 存在 false不存在
300 */
301 public boolean sHasKey(String key,Object value){
302 try {
303 return redisTemplate.opsForSet().isMember(key, value);
304 } catch (Exception e) {
305 e.printStackTrace();
306 return false;
307 }
308 }
309
310 /**
311 * 将数据放入set缓存
312 * @param key 键
313 * @param values 值 可以是多个
314 * @return 成功个数
315 */
316 public long sSet(String key, Object...values) {
317 try {
318 return redisTemplate.opsForSet().add(key, values);
319 } catch (Exception e) {
320 e.printStackTrace();
321 return 0;
322 }
323 }
324
325 /**
326 * 将set数据放入缓存
327 * @param key 键
328 * @param time 时间(秒)
329 * @param values 值 可以是多个
330 * @return 成功个数
331 */
332 public long sSetAndTime(String key,long time,Object...values) {
333 try {
334 Long count = redisTemplate.opsForSet().add(key, values);
335 if(time>0) {
336 expire(key, time);
337 }
338 return count;
339 } catch (Exception e) {
340 e.printStackTrace();
341 return 0;
342 }
343 }
344
345 /**
346 * 获取set缓存的长度
347 * @param key 键
348 * @return
349 */
350 public long sGetSetSize(String key){
351 try {
352 return redisTemplate.opsForSet().size(key);
353 } catch (Exception e) {
354 e.printStackTrace();
355 return 0;
356 }
357 }
358
359 /**
360 * 移除值为value的
361 * @param key 键
362 * @param values 值 可以是多个
363 * @return 移除的个数
364 */
365 public long setRemove(String key, Object ...values) {
366 try {
367 Long count = redisTemplate.opsForSet().remove(key, values);
368 return count;
369 } catch (Exception e) {
370 e.printStackTrace();
371 return 0;
372 }
373 }
374 //===============================list=================================
375
376 /**
377 * 获取list缓存的内容
378 * @param key 键
379 * @param start 开始
380 * @param end 结束 0 到 -1代表所有值
381 * @return
382 */
383 public List<Object> lGet(String key, long start, long end){
384 try {
385 return redisTemplate.opsForList().range(key, start, end);
386 } catch (Exception e) {
387 e.printStackTrace();
388 return null;
389 }
390 }
391
392 /**
393 * 获取list缓存的长度
394 * @param key 键
395 * @return
396 */
397 public long lGetListSize(String key){
398 try {
399 return redisTemplate.opsForList().size(key);
400 } catch (Exception e) {
401 e.printStackTrace();
402 return 0;
403 }
404 }
405
406 /**
407 * 通过索引 获取list中的值
408 * @param key 键
409 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
410 * @return
411 */
412 public Object lGetIndex(String key,long index){
413 try {
414 return redisTemplate.opsForList().index(key, index);
415 } catch (Exception e) {
416 e.printStackTrace();
417 return null;
418 }
419 }
420
421 /**
422 * 将list放入缓存
423 * @param key 键
424 * @param value 值
425 * @return
426 */
427 public boolean lSet(String key, Object value) {
428 try {
429 redisTemplate.opsForList().rightPush(key, value);
430 return true;
431 } catch (Exception e) {
432 e.printStackTrace();
433 return false;
434 }
435 }
436
437 /**
438 * 将list放入缓存
439 * @param key 键
440 * @param value 值
441 * @param time 时间(秒)
442 * @return
443 */
444 public boolean lSet(String key, Object value, long time) {
445 try {
446 redisTemplate.opsForList().rightPush(key, value);
447 if (time > 0) {
448 expire(key, time);
449 }
450 return true;
451 } catch (Exception e) {
452 e.printStackTrace();
453 return false;
454 }
455 }
456
457 /**
458 * 将list放入缓存
459 * @param key 键
460 * @param value 值
461 * @return
462 */
463 public boolean lSet(String key, List<Object> value) {
464 try {
465 redisTemplate.opsForList().rightPushAll(key, value);
466 return true;
467 } catch (Exception e) {
468 e.printStackTrace();
469 return false;
470 }
471 }
472
473 /**
474 * 将list放入缓存
475 * @param key 键
476 * @param value 值
477 * @param time 时间(秒)
478 * @return
479 */
480 public boolean lSet(String key, List<Object> value, long time) {
481 try {
482 redisTemplate.opsForList().rightPushAll(key, value);
483 if (time > 0) {
484 expire(key, time);
485 }
486 return true;
487 } catch (Exception e) {
488 e.printStackTrace();
489 return false;
490 }
491 }
492
493 /**
494 * 根据索引修改list中的某条数据
495 * @param key 键
496 * @param index 索引
497 * @param value 值
498 * @return
499 */
500 public boolean lUpdateIndex(String key, long index,Object value) {
501 try {
502 redisTemplate.opsForList().set(key, index, value);
503 return true;
504 } catch (Exception e) {
505 e.printStackTrace();
506 return false;
507 }
508 }
509
510 /**
511 * 移除N个值为value
512 * @param key 键
513 * @param count 移除多少个
514 * @param value 值
515 * @return 移除的个数
516 */
517 public long lRemove(String key,long count,Object value) {
518 try {
519 Long remove = redisTemplate.opsForList().remove(key, count, value);
520 return remove;
521 } catch (Exception e) {
522 e.printStackTrace();
523 return 0;
524 }
525 }
526
527 /**
528 * 模糊查询获取key值
529 * @param pattern
530 * @return
531 */
532 public Set keys(String pattern){
533 return redisTemplate.keys(pattern);
534 }
535
536 /**
537 * 使用Redis的消息队列
538 * @param channel
539 * @param message 消息内容
540 */
541 public void convertAndSend(String channel, Object message){
542 redisTemplate.convertAndSend(channel,message);
543 }
544
545
546 //=========BoundListOperations 用法 start============
547
548 /* *//**
549 *将数据添加到Redis的list中(从右边添加)
550 * @param listKey
551 * @param expireEnum 有效期的枚举类
552 * @param values 待添加的数据
553 *//*
554 public void addToListRight(String listKey, Status.ExpireEnum expireEnum, Object... values) {
555 //绑定操作
556 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
557 //插入数据
558 boundValueOperations.rightPushAll(values);
559 //设置过期时间
560 boundValueOperations.expire(expireEnum.getTime(),expireEnum.getTimeUnit());
561 }*/
562 /**
563 * 根据起始结束序号遍历Redis中的list
564 * @param listKey
565 * @param start 起始序号
566 * @param end 结束序号
567 * @return
568 */
569 public List<Object> rangeList(String listKey, long start, long end) {
570 //绑定操作
571 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
572 //查询数据
573 return boundValueOperations.range(start, end);
574 }
575 /**
576 * 弹出右边的值 --- 并且移除这个值
577 * @param listKey
578 */
579 public Object rifhtPop(String listKey){
580 //绑定操作
581 BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
582 return boundValueOperations.rightPop();
583 }
584
585 }
6.使用自定义Redis工具类
@Autowiredprivate RedisUtils redisUtils;完事!!!