本文共 2771 字,大约阅读时间需要 9 分钟。
@Getterpublic 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 ListgetCurrentUserAclListFromCache() { int userId = RequestHolder.getCurrentUser().getId(); String cacheValue = sysCacheService.getFromCache(CacheKeyConstants.USER_ACLS, String.valueOf(userId)); //缓存中没有 if (StringUtils.isBlank(cacheValue)) { //数据库取 List 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
>() { }); }
转载地址:http://itphn.baihongyu.com/