【项目实战】-- redis的使用(一)

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);
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值