SearchCacheService.java
3.24 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.yoho.search.cache.beans;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yoho.core.redis.cluster.operations.serializer.RedisKeyBuilder;
import com.yoho.search.cache.model.CacheObject;
import com.yoho.search.cache.model.SearchCache;
import com.yoho.search.common.SearchServiceConfiger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
@Service
public class SearchCacheService {
private static final Logger logger = LoggerFactory.getLogger(SearchCacheService.class);
@Autowired
private SearchServiceConfiger searchServiceConfiger;
private void addObjectToCache(RedisKeyBuilder redisKeyBuilder, Object object, SearchCache searchCache) {
// 1、如果不适用缓存,则直接返回
if (!searchServiceConfiger.useCache()) {
return;
}
// 2、如果缓存不存在,则直接返回
if (searchCache == null || searchCache.getCache() == null) {
return;
}
// 3、加入缓存
CacheObject cacheObject = new CacheObject(object);
searchCache.getCache().addOrUpdate(redisKeyBuilder, cacheObject, searchCache.getCacheInMinute());
}
/**
* 从缓存中取数据
*
* @param redisKeyBuilder
* @return
*/
private CacheObject getCacheObjectFromCache(RedisKeyBuilder redisKeyBuilder, SearchCache searchCache) {
// 1、如果不适用缓存,则直接返回
if (!searchServiceConfiger.useCache()) {
return null;
}
// 2、如果缓存不存在,则直接返回
if (searchCache == null || searchCache.getCache() == null) {
return null;
}
// 3、增加缓存访问次数
searchCache.incTotalCount();
// 4、从缓存中获取cacheObject
CacheObject cacheObject = searchCache.getCache().get(redisKeyBuilder);
// 5、如果从缓存中拿不到数据,则直接返回
if (cacheObject == null) {
return null;
}
// 6、增加缓存命中次数,并返回缓存对象
searchCache.incMatchCount();
return cacheObject;
}
public <T> T getSerializableObjectFromCache(SearchCache searchCache, RedisKeyBuilder redisKeyBuilder, Type type) {
try {
CacheObject cacheObject = this.getCacheObjectFromCache(redisKeyBuilder, searchCache);
if (cacheObject == null) {
return null;
}
String stringValue = (String) cacheObject.toObject();
return JSON.parseObject(stringValue, type);
} catch (Exception e) {
logger.error(e.getMessage(),e);
return null;
}
}
public <T> void addSerializableObjectToCache(SearchCache searchCache, RedisKeyBuilder redisKeyBuilder, T object) {
String jsonStr = JSON.toJSONString(object, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
this.addObjectToCache(redisKeyBuilder, jsonStr, searchCache);
}
}