一、自定义KEY
@Getter
public enum CacheKeyConstants {
SYSTEM_ACLS,
USER_ACLS;
}
二、实现
1、首先生成key
2、拿到连接池
3、调用redis的方法
public class SysCacheService {
@Resource(name = "redisPool")
private RedisPool redisPool;
//CacheKeyConstants指定前缀,系统级别
public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
saveCache(toSavedValue, timeoutSeconds, prefix, null);
}
//用户级别的
public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
if (toSavedValue == null) {
return;
}
ShardedJedis shardedJedis = null;
try {
//首先生成key
String cacheKey = generateCacheKey(prefix, keys);
//拿到资源
shardedJedis = redisPool.instance();
//调用redis方法
shardedJedis.setex(cacheKey, timeoutSeconds, toSavedValue);
} catch (Exception e) {
log.error("save cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
} finally {
redisPool.safeClose(shardedJedis);
}
}
public String getFromCache(CacheKeyConstants prefix, String... keys) {
ShardedJedis shardedJedis = null;
String cacheKey = generateCacheKey(prefix, keys);
try {
shardedJedis = redisPool.instance();
String value = shardedJedis.get(cacheKey);
return value;
} catch (Exception e) {
log.error("get from cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
return null;
} finally {
redisPool.safeClose(shardedJedis);
}
}
//生成CacheKey方法
private String generateCacheKey(CacheKeyConstants prefix, String... keys) {
String key = prefix.name();
if (keys != null && keys.length > 0) {
key += "_" + Joiner.on("_").join(keys);
}
return key;
}
}
三、缓存加在哪里?
缓存会造成数据的延缓:需要特定场景(假如加在拦截上,拦截会查多次数据库,更新的时候缓存会给管理员造成困惑,不知道是否做了更新)
这里举例:加载查询当前用户所有权限上,用户的每一次访问,都会从查是否拥有这个权限,所有可以加在这里,缓解数据库类压力
public List<SysAcl> getCurrentUserAclListFromCache() {
int userId = RequestHolder.getCurrentUser().getId();
String cacheValue = sysCacheService.getFromCache(CacheKeyConstants.USER_ACLS, String.valueOf(userId));
//缓存中没有
if (StringUtils.isBlank(cacheValue)) {
//数据库取
List<SysAcl> aclList = getCurrentUserAclList();
if (CollectionUtils.isNotEmpty(aclList)) {
sysCacheService.saveCache(JsonMapper.obj2String(aclList), 600, CacheKeyConstants.USER_ACLS, String.valueOf(userId));
}
return aclList;
}
return JsonMapper.string2Obj(cacheValue, new TypeReference<List<SysAcl>>() {
});
}