Redis与序列化反序列化

Redis与序列化反序列化

SpringBoot自带JSON

1
2
3
4
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@Component
public class RedisUtil {

@Autowired
private StringRedisTemplate stringRedisTemplate;

private final ObjectMapper objectMapper = new ObjectMapper();

/**
* 设置键值对(对象序列化为JSON存储),并设置过期时间
*/
public <T> void set(String key, T value, long timeout) {
try {
String json = objectMapper.writeValueAsString(value);
stringRedisTemplate.opsForValue().set(key, json, timeout, TimeUnit.MINUTES);
} catch (Exception e) {
throw new RuntimeException("Redis set operation failed", e);
}
}

/**
* 获取值(JSON反序列化为对象)
*/
public <T> T get(String key, TypeReference<T> typeReference) {
try {
String json = stringRedisTemplate.opsForValue().get(key);
if (json == null) {
return null;
}
return objectMapper.readValue(json, typeReference);
} catch (Exception e) {
throw new RuntimeException("Redis get operation failed", e);
}
}

/**
* 删除键
*/
public void delete(String key) {
stringRedisTemplate.delete(key);
}
}

Redis与序列化反序列化
https://www.zheep.top/2024/11/26/Redis与序列化反序列化/
作者
西行寺岩羊
发布于
2024年11月26日
许可协议