Spring Boot中使用RedisTemplate存储实体对象
刚好最近在弄这个,顺便记录一下。使用RedisTemplate来存储实体对象。 Spring Boot 版本是 2.2.9.RELEASE
1. 引入依赖
pom.xml
代码语言:javascript复制 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
配置文件:
代码语言:javascript复制Spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
password: 12345678
2. 连接配置
使用 fastjson 进行序列化,FastJsonRedisSerializer.java
代码语言:javascript复制
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
*
* @author lixiaojin
* @date 2021/6/11 22:29
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (null == t) {
return new byte[0];
}
if (t instanceof String) {
return t.toString().getBytes();
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (null == bytes || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
//是否打开autoType
ParserConfig.getGlobalInstance().setAutoTypeSupport(false);
return JSON.parseObject(str, clazz);
}
}
Redis连接配置,ClusterRedisConfiguration.java
代码语言:javascript复制/**
* @author lixiaojin
* @date 2021/6/11 22:29
*/
@Configuration
public class ClusterRedisConfiguration {
@Resource
private Environment env;
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(200);
jedisPoolConfig.setMaxIdle(150);
jedisPoolConfig.setMinIdle(50);
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(env.getProperty("spring.redis.host"));
redisStandaloneConfiguration.setPort(Integer.parseInt(env.getProperty("spring.redis.port")));
redisStandaloneConfiguration.setPassword(env.getProperty("spring.redis.password"));
redisStandaloneConfiguration.setDatabase(Integer.parseInt(env.getProperty("spring.redis.database")));
JedisClientConfiguration.JedisClientConfigurationBuilder configurationBuilder = JedisClientConfiguration.builder();
JedisClientConfiguration jedisClientConfiguration = configurationBuilder.usePooling().poolConfig(jedisPoolConfig).build();
return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
}
/**
* 缓存模板--对象序列化
*/
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//使用fastJson序列化
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
//value值序列化
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
//key值序列化
template.setKeySerializer(fastJsonRedisSerializer);
template.setHashKeySerializer(fastJsonRedisSerializer);
//设置连接
template.setConnectionFactory(jedisConnectionFactory);
return template;
}
}
3. RedisTemplate 工具类
代码语言:javascript复制
/**
* @param <T>
* @author lixiaojin
* @date 2021-06-11
*/
@Component
public class RedisCacheUtils<T> {
@Resource
private RedisTemplate<String, T> redisTemplate;
/**
* 获取存储的对象
*
* @param key key
* @return 对象
*/
public T getObject(String key) {
if (StringUtil.isEmpty(key)) {
return null;
}
return redisTemplate.opsForValue().get(key);
}
/**
* 存入对象类型数据
*
* @param key redis key
* @param value redis value
*/
public boolean setObject(String key, T value) {
return setObject(key, value, 0);
}
/**
* 存入对象类型数据,设置存储时间
*
* @param key key
* @param value value
* @param time 存放时间
*/
public boolean setObject(String key, T value, long time) {
if (StringUtil.isEmpty(key) || value == null) {
return false;
}
if (time == 0) {
redisTemplate.opsForValue().set(key, value);
} else {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
return true;
}
/**
* 重新设置对象失效时间
*
* @param key
* @param time
* @return
*/
public boolean addObjInvalidTime(String key, long time) {
if (StringUtil.isEmpty(key) && redisTemplate.getExpire(key) <= 0) {
return false;
}
return redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
/**
* 根据key 清除缓存
*
* @param key key
* @return 清楚结果
*/
public boolean removeObj(String key) {
if (StringUtil.isEmpty(key)) {
return false;
}
redisTemplate.delete(key);
return true;
}
}
4. 使用例子
代码语言:javascript复制/**
* @author lixiaojin
* @date 2021/6/11 21:55
*/
public class TestController {
@Resource
private RedisCacheUtils<UserVo> redisCache;
@GetMapping("set")
public Boolean testSet(@RequestParam String key, @RequestParam String value) {
UserVo user = new UserVo().setId("123456")
.setMobile("18888888888")
.setName("sss")
.setOrgId("111")
.setOrgCode("s");
return redisCache.setObject(key, user);
}
@GetMapping("get")
public UserVo testGet(@RequestParam String key) {
return redisCache.getObject(key);
}
}
使用 RedisDesktopManager 查看 Redis,这是使用 RedisTemplate 存储的样子,会有一个 @type 字段,虽然也是转换为字符串,但是通过 getObject() 方法获取的时候会转换为我们设置的对象类型,使用起来比较方便。
代码语言:javascript复制{
"@type": "com.test.lixj.vo.UserVo",
"id": "123456",
"mobile": "18888888888",
"name": "sss",
"orgCode": "s",
"orgId": "111"
}
以下是使用 StringRedisTemplate 存储时的样子,存储的是字符串,通过 get() 方法取出的时候只是字符串,需要我们拿到字符串后再转化为指定的对象。
代码语言:javascript复制{
"id": "123456",
"mobile": "18888888888",
"name": "sss",
"orgCode": "s",
"orgId": "111"
}
使用上的区别大概就是这样,可以根据场景去选择。
Copyright: 采用 知识共享署名4.0 国际许可协议进行许可 Links: https://lixj.fun/archives/springboot中使用redistemplate存储实体对象