1.批量获取缓存
stringList = redisClient.invoke(t -> t.hmget(CACHE_KEY_DOMAIN_ITEM, Converter.toStringArray(keys)));
2.加入缓存
JsonDetailInfo jsonDetailInfo = getJsonDetailInfoByRespItem(rcmdKey, item + "", article, selfmediaAccount,
articleCountMap.get(articleId));
// 加入缓存
setCacheItem(itemId, RECOMMENDTYPE, result);
/**
* 设置缓存
*
* @param feedId
* @param type
* @param detailInfo
*/
private void setCacheItem(String feedId, String type, JsonDetailInfo detailInfo) {
if (detailInfo == null) {
return;
}
try {
String key = String.format(CACHE_KEY_FORMAT, feedId, type);
String content = encoder.encode(detailInfo);
Long aLong = redisClient.invoke(t -> t.ttl(CACHE_KEY_DOMAIN_ITEM));
redisClient.setHSet(CACHE_KEY_DOMAIN_ITEM, key, content);
if (aLong == null || aLong < 0) {
redisClient.expire(CACHE_KEY_DOMAIN_ITEM, CACHE_TIME_SECOND);
}
} catch (Exception e) {
logger.error("set cache err", e);
}
}
/**
* 执行自定义操作
*
* @param func 操作执行者
*/
public <T> T invoke(Function<ShardedJedis, T> func) {
ShardedJedis jedis = null;
try {
jedis = getMasterPool().getResource();
return func.apply(jedis);
} catch (JedisException e) {
logger.error("invoke failed", e);
throw e;
} finally {
close(jedis);
}
}
/**
* 设置HashSet对象
*
* @param domain 域名
* @param key 键值
* @param value Json String or String value
* @return
*/
public boolean setHSet(String domain, String key, String value) {
if (value == null) {
return false;
}
ShardedJedis jedis = null;
try {
jedis = getMasterPool().getResource();
jedis.hset(domain, key, value);
return true;
} catch (Exception e) {
logger.error("setHSet error.", e);
throw e;
} finally {
close(jedis);
}
}
/**
* 设置缓存过期时间
*
* @param key
* @param seconds
* @return
*/
public Long expire(String key, int seconds) {
ShardedJedis jedis = null;
try {
jedis = getMasterPool().getResource();
return jedis.expire(key, seconds);
} catch (JedisException e) {
logError(e, jedis, "expire", key);
throw e;
} finally {
close(jedis);
}
}