RedisCacheUtils.java
1.84 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.yoho.search.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yoho.core.redis.cluster.operations.nosync.YHRedisTemplate;
import com.yoho.core.redis.cluster.operations.nosync.YHValueOperations;
import com.yoho.core.redis.cluster.operations.serializer.RedisKeyBuilder;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.TimeUnit;
public class RedisCacheUtils {
public static <T> T get(YHValueOperations valueOperations, String key, Class<T> clazz) {
RedisKeyBuilder keyBuilder = RedisKeyBuilder.newInstance().appendFixed(key);
String compressedVal = valueOperations.get(keyBuilder);
if (StringUtils.isBlank(compressedVal)) {
return null;
}
String uncompressStr = SnappyUtils.uncompress(compressedVal);
return unserializeFromString(uncompressStr, clazz);
}
public static <T> void add(YHValueOperations valueOperations, String key, T t, int expiredTimeInMinute) {
String uncompressStr = serializeToString(t);
String compressedVal = SnappyUtils.compress(uncompressStr);
if (StringUtils.isBlank(compressedVal)) {
return;
}
RedisKeyBuilder keyBuilder = RedisKeyBuilder.newInstance().appendFixed(key);
valueOperations.set(keyBuilder, compressedVal, expiredTimeInMinute, TimeUnit.MINUTES);
}
public static void delete(YHRedisTemplate redisTemplate, String key) {
redisTemplate.delete(key);
}
public static boolean exist(YHRedisTemplate redisTemplate, String key) {
return redisTemplate.hasKey(key);
}
/**
* 序列化保持null值
*
* @param t
* @return
*/
private static <T> String serializeToString(T t) {
return JSON.toJSONString(t, SerializerFeature.WriteMapNullValue);
}
private static <T> T unserializeFromString(String cacheObjectValue, Class<T> clazz) {
return JSON.parseObject(cacheObjectValue, clazz);
}
}