SpringBoot 中 StringRedisTemplate 和 RedisTemplate 的区别及用法
一、RedisTemplate和StringRedisTemplate的区别
两者的关系是StringRedisTemplate继承RedisTemplate。
两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。
SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
- StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的(StringRedisSerializer)。
- RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。(JdkSerializationRedisSerializer)
- StringRedisTemplate 相对于 RedisTemplate 的使用,只是把 @Autowired 注入的进行更改就行。在具体的使用方面,这两个区别性不大。
- StringRedisTemplate:当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候。
- RedisTemplate:但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象。
使用的区别
RedisTemplate使用的序列类在在操作数据的时候,比如说存入数据会将数据先序列化成字节数组然后在存入Redis数据库,这个时候打开Redis查看的时候,你会看到你的数据不是以可读的形式展现的,而是以字节数组显示,类似下面(RedisTemplate)
当然从Redis获取数据的时候也会默认将数据当做字节数组转化,这样就会导致一个问题,当需要获取的数据不是以字节数组存在redis当中而是正常的可读的字符串的时候,比如说下面这种形式的数据(StringRedisTemplate)
- 当Redis当中的数据值是以数组形式显示出来的时候,只能使用RedisTemplate才能获取到里面的数据。
- 当Redis当中的数据值是以可读的形式显示出来的时候,只能使用StringRedisTemplate才能获取到里面的数据。
- 所以当你使用RedisTemplate获取不到数据为NULL时,一般是获取的方式错误。检查一下数据是否可读即可。
二、StringRedistemplate 和 Redistemplate 的序列化
1、StringRedistemplate的源码及序列化如下:
package org.springframework.data.redis.core;
import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
public class StringRedisTemplate extends RedisTemplate<String, String> {
public StringRedisTemplate() {
this.setKeySerializer(RedisSerializer.string());
this.setValueSerializer(RedisSerializer.string());
this.setHashKeySerializer(RedisSerializer.string());
this.setHashValueSerializer(RedisSerializer.string());
}
public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
this.setConnectionFactory(connectionFactory);
this.afterPropertiesSet();
}
protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}
从上面创建StringRedisTemplate的无参构造方法可以看出,此时将keySerializer、valueSerializer、hashKeySerializer、hashValueSerializer的序列化方式为stringSerializer,也就是StringRedisSerializer序列化方式;此时执行完整个方法后,还需要接着执行setConnectionFactory()方法,然后转向他的父类RedisTemplate中的afterPropertiesSet方法,此时上述四个序列化方式已经设置;
2、Redistemplate的序列化如下:
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.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 1.创建 redisTemplate 模版
RedisTemplate<Object, Object> template = new RedisTemplate<>();
// 2.关联 redisConnectionFactory
template.setConnectionFactory(redisConnectionFactory);
// 3.创建 序列化类
GenericToStringSerializer genericToStringSerializer = new GenericToStringSerializer(Object.class);
// 6.序列化类,对象映射设置
// 7.设置 value 的转化格式和 key 的转化格式
template.setValueSerializer(genericToStringSerializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
四、实例:StringRedisTemplate 的使用
1、前提
pom.xml依赖
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
properties配置文件如下:
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000ms
2、存入String类型的工具类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class StringRedisUtils {
@Autowired
private StringRedisTemplate stringRedisTemplate;
// Redis的默认保存时间
@Value(value = "${redis.keepTime}")
private int redisKeepTime=5;
/**
* 添加数据到Redis中
*
* @param key
* @param value
*/
public void addRedis(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
/**
* 添加数据到Redis中(自定义保存时间)
*
* @param key
* @param value
*/
public void addRedisTime(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value, redisKeepTime, TimeUnit.MINUTES);
}
/**
* 根据key获取Redis中数据
*
* @param key
* @return
*/
public String getRedis(String key) {
String value = stringRedisTemplate.opsForValue().get(key);
return value;
}
/**
* 根据key删除Redis中的数据
*
* @param key
* @return
*/
public boolean deleteRedis(String key) {
Boolean result = stringRedisTemplate.delete(key);
return result;
}
/**
* 设置Redis的保存时间
*
* @param key
* @param time
*/
public void setRedisTime(String key, int time) {
stringRedisTemplate.expire(key, time, TimeUnit.MINUTES);
}
}
3、web调用进行测试
import com.ccasd.redis.StringRedisUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/excel")
public class WordExcelController {
private static final Logger logger = LogManager.getLogger(WordExcelController.class);
@Autowired
private StringRedisUtils stringRedisUtils;
/**
* 测试_向Redis中插入数据
* @param en
* @throws Exception
*/
@RequestMapping(value = "/add", method = {RequestMethod.POST})
public void add(@RequestBody Map<String, String> en) throws Exception {
String key = en.get("key").toString();
String value = en.get("value").toString();
stringRedisUtils.addRedis(key, value);
}
/**
* 测试_从Redis中查询数据
* @param en
* @return
* @throws Exception
*/
@RequestMapping(value = "/get", method = {RequestMethod.POST})
public String get(@RequestBody Map<String, Object> en) throws Exception {
String key = en.get("key").toString();
String value = stringRedisUtils.getRedis(key);
return value;
}
}