# SpringRedisTemplate **Repository Path**: kaifa996/spring-redis-template ## Basic Information - **Project Name**: SpringRedisTemplate - **Description**: SpringRedisTemplate - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2023-11-15 - **Last Updated**: 2024-08-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README @[TOC](文章预览:) # 简介 **案例中使用的是StringRedisTemplate至于为什么不用RedisTemplate的原因如下:** 实际生产项目当中使用StringRedisTemplate来进行缓存数据的更多; [对于使用RedisTemplate案例的分析](https://blog.csdn.net/weixin_43811057/article/details/130735304) >在我们为**RedisTemplate指定序列化方式后(`key为RedisSerializer.string()`,`value为GenericJackson2JsonRedisSerializer`),我们存储value为实体类对象时**,会产生如下现象: ![在这里插入图片描述](https://img-blog.csdnimg.cn/c9bd8f36023847a5a91005535b5a5a07.png) 这是因为,当我们传入的**Value为实体类对象**的时候,会用 `GenericJackson2JsonRedisSerializer`序列化器把`java对象转为JSON格式`,然后再存入Redis库中,在我们使用`redisTemplate.opsForValue().get方法`获取数据时,通过存入的`@class`属性,把`JSON`反序列化成JAVA对象。 这样一来我们在IDEA的控制器上很直观的就可以看到数据,但是也存在了一个缺点->浪费内存,因为我们要存放@class这一段额外的数据来反序列化JSON字符串。 那为了节约内存,我们在处理`Value`时不使用`GenericJackson2JsonRedisSerializer序列化器`,使用`RedisSerializer.string序列化器`。这样一下,我们只需要在存入数据时,**手动的把JAVA对象转变为JSON格式字符串,然后取数据时,再把JSON转回JAVA对象就好了。** ==而StringRedisTemplate它的key和Value默认就是String方式,我们不用自己再去定义RedisTemplate的配置类。== # 一、创建springboot项目(采用骨架方式) ```cpp 1.使用 StringRedisTemplate 2.写入 Redis 时,手动把对象序列化为 JSON 3.读取 Redis 时,手动把读取到的 JSON 反序列化为对象 ``` [案例源码](https://gitee.com/wl8888/spring-redis-template.git) ![在这里插入图片描述](https://img-blog.csdnimg.cn/33d54d3d061a46bcbd27f88e804f33b9.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ![在这里插入图片描述](https://img-blog.csdnimg.cn/7e96d20f9e1742f0972de1d0e1353b6f.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ![在这里插入图片描述](https://img-blog.csdnimg.cn/9d07a333df274446914c84376e8bad44.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ![在这里插入图片描述](https://img-blog.csdnimg.cn/c270f6f6b31b49858d7ea5752f382f41.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ![在这里插入图片描述](https://img-blog.csdnimg.cn/42ae6306aaa341f88d0896a1e90620c1.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ![在这里插入图片描述](https://img-blog.csdnimg.cn/489616f0e49c4e3cb395295bd1665af4.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_18,color_FFFFFF,t_70,g_se,x_16) 创建完成; 我们分析下pom文件中内容: 所使用到的关键依赖: ```xml org.springframework.boot spring-boot-starter-data-redis 2.5.4 org.springframework.boot spring-boot-starter-web 2.5.4 org.projectlombok lombok 1.18.20 true org.springframework.boot spring-boot-starter-test 2.5.4 test org.springframework.boot spring-boot-autoconfigure 2.5.4 com.alibaba fastjson 1.2.75 ``` # 二、配置文件 ```yml server.port=8088 spring.redis.host=127.0.0.1 #Redis服务器连接端口 spring.redis.port=6379 #Redis服务器连接密码(默认为空) spring.redis.password=123456 #连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 #连接池中的最大空闲连接 spring.redis.pool.max-idle=8 #连接池中的最小空闲连接 spring.redis.pool.min-idle=0 #连接超时时间(毫秒) spring.redis.timeout=30000 ``` # 三、使用redis ```java package com.example.redis.cache; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * @author wxl * @date 2021-08-15 18:44 */ @Slf4j @Component public class CacheService { @Autowired private StringRedisTemplate redisTemplate; private final String DEFAULT_KEY_PREFIX = ""; private final int EXPIRE_TIME = 1; private final TimeUnit EXPIRE_TIME_TYPE = TimeUnit.DAYS; /** * 数据缓存至redis * * @param key * @param value * @return */ public void add(K key, V value) { try { if (value != null) { redisTemplate .opsForValue() .set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value)); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("数据缓存至redis失败"); } } /** * 数据缓存至redis并设置过期时间 * * @param key * @param value * @return */ public void add(K key, V value, long timeout, TimeUnit unit) { try { if (value != null) { redisTemplate .opsForValue() .set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value), timeout, unit); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("数据缓存至redis失败"); } } /** * 写入 hash-set,已经是key-value的键值,不能再写入为hash-set * * @param key must not be {@literal null}. * @param subKey must not be {@literal null}. * @param value 写入的值 */ public void addHashCache(K key, SK subKey, V value) { redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value); } /** * 写入 hash-set,并设置过期时间 * * @param key must not be {@literal null}. * @param subKey must not be {@literal null}. * @param value 写入的值 */ public void addHashCache(K key, SK subKey, V value, long timeout, TimeUnit unit) { redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value); redisTemplate.expire(DEFAULT_KEY_PREFIX + key, timeout, unit); } /** * 获取 hash-setvalue * * @param key must not be {@literal null}. * @param subKey must not be {@literal null}. */ public Object getHashCache(K key, SK subKey) { return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX + key, subKey); } /** * 从redis中获取缓存数据,转成对象 * * @param key must not be {@literal null}. * @param clazz 对象类型 * @return */ public V getObject(K key, Class clazz) { String value = this.get(key); V result = null; if (!StringUtils.isEmpty(value)) { result = JSONObject.parseObject(value, clazz); } return result; } /** * 从redis中获取缓存数据,转成list * * @param key must not be {@literal null}. * @param clazz 对象类型 * @return */ public List getList(K key, Class clazz) { String value = this.get(key); List result = Collections.emptyList(); if (!StringUtils.isEmpty(value)) { result = JSONArray.parseArray(value, clazz); } return result; } /** * 功能描述:Get the value of {@code key}. * * @param key must not be {@literal null}. * @return java.lang.String * @date 2021/9/19 **/ public String get(K key) { String value; try { value = redisTemplate.opsForValue().get(DEFAULT_KEY_PREFIX + key); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException("从redis缓存中获取缓存数据失败"); } return value; } /** * 删除key */ public void delete(String key) { redisTemplate.delete(key); } /** * 批量删除key */ public void delete(Collection keys) { redisTemplate.delete(keys); } /** * 序列化key */ public byte[] dump(String key) { return redisTemplate.dump(key); } /** * 是否存在key */ public Boolean hasKey(String key) { return redisTemplate.hasKey(key); } /** * 设置过期时间 */ public Boolean expire(String key, long timeout, TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); } /** * 设置过期时间 */ public Boolean expireAt(String key, Date date) { return redisTemplate.expireAt(key, date); } /** * 移除 key 的过期时间,key 将持久保持 */ public Boolean persist(String key) { return redisTemplate.persist(key); } /** * 返回 key 的剩余的过期时间 */ public Long getExpire(String key, TimeUnit unit) { return redisTemplate.getExpire(key, unit); } /** * 返回 key 的剩余的过期时间 */ public Long getExpire(String key) { return redisTemplate.getExpire(key); } } ``` ## 1、添加字符串到redis ```java /** * 功能描述:添加字符串到redis */ @Test void add() { cacheService.add("test", 1234); } ``` 结果: ![在这里插入图片描述](https://img-blog.csdnimg.cn/6111e6b314a3470093c24e4afb8ee0da.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ## 2、将对象转换成jsonString并存入redis ```java /** * 功能描述:添加对象至redis */ @Test void addObject() { User user = User.builder() .id(ID) .name("小萌") .age(AGE) .build(); cacheService.add(user.getId(), user); } ``` 结果:![在这里插入图片描述](https://img-blog.csdnimg.cn/de171481b0144233997d02c8ebe7087c.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ## 3、将对象集合转换成jsonString,并设置过期时间存入至redis ```java /** * 功能描述:添加对象集合至redis */ @Test void addObjects() { ArrayList users = new ArrayList<>(); User user = User.builder() .id(ID) .name("小萌") .age(AGE) .build(); users.add(user); cacheService.add("key", users, 1, TimeUnit.HOURS); } ``` 结果: ![在这里插入图片描述](https://img-blog.csdnimg.cn/3a98157124d44a3f9a2c9581bdb044fa.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ## 4、获取对象 ```java /** * 功能描述:获取对象 */ @Test void getObject() { User object = cacheService.getObject(ID, User.class); System.out.println("object = " + object); } ``` 结果: ```java object = User(id=123, name=小萌, age=12) ``` ## 5、获取对象集合 ```java /** * 功能描述:获取对象集合 */ @Test void getObjects() { List users = cacheService.getList("key", User.class); System.out.println("users = " + users); } ``` 结果: ```java users = [User(id=123, name=小萌, age=12)] ``` ## 6、添加 hash-set ```java /** * 功能描述:添加 hash-set */ @Test void addHashCache() { cacheService.addHashCache("hashKey", "key", "value"); } ``` 结果: ![在这里插入图片描述](https://img-blog.csdnimg.cn/b3a701944a094930a876d03b5720d5f5.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LyP5Yqg54m56YGH5LiK6KW_5p-a,size_20,color_FFFFFF,t_70,g_se,x_16) ## 7、获取 hash-setvalue ```java /** * 功能描述:获取 hash-set */ @Test void getHashCache() { Object hashCache = cacheService.getHashCache("hashKey", "key"); System.out.println("hashCache = " + hashCache); } ``` 结果: ```java hashCache = value ``` 上一篇:[SpringDataRedis](https://blog.csdn.net/weixin_43811057/article/details/130735304?csdn_share_tail=%7B%22type%22:%22blog%22,%22rType%22:%22article%22,%22rId%22:%22130735304%22,%22source%22:%22weixin_43811057%22%7D)