RedisValueCache.java 2.67 KB
package com.yohoufo.user.cache;

import com.yoho.core.redis.cluster.annotation.Redis;
import com.yoho.core.redis.cluster.operations.nosync.YHRedisTemplate;
import com.yoho.core.redis.cluster.operations.nosync.YHValueOperations;
import com.yoho.core.redis.cluster.operations.serializer.RedisKeyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhouxiang on 2016/5/31.
 */
@Component
public class RedisValueCache {

    private final static Logger logger = LoggerFactory.getLogger(RedisValueCache.class);

    @Redis("yohoNoSyncRedis")
    YHRedisTemplate yHRedisTemplate;

    @Redis("yohoNoSyncRedis")
    YHValueOperations yhValueOperations;


    public Long incrementWithExpire(RedisKeyBuilder cacheKey, long delta , long timeout, TimeUnit unit) {
        logger.debug("Enter increment valueOperation redis.key is {},delta is {}", cacheKey, delta);
        try {
            Long num =  yhValueOperations.increment(cacheKey, delta);
            yHRedisTemplate.longExpire(cacheKey, timeout, unit);
            return num;
        } catch (Exception e) {
            try{
                yHRedisTemplate.longExpire(cacheKey, timeout, unit);
            }catch (Exception e1){
                logger.error("RedisValueHelper expire redis again error. with key={}", cacheKey, e1);
            }
            logger.warn("Redis exception. increment fail,key {},delta is {}, error msg is {}", cacheKey, delta, e);
        }
        return 0L;
    }


    /**
     * 设置值
     *
     * @param cacheKey
     * @param value
     * @param timeout
     * @param unit
     * @param <T>
     */
    public <T> void set(RedisKeyBuilder cacheKey, T value, long timeout, TimeUnit unit) {
        logger.debug("Enter set valueOperation redis value.key is {},value is {}", cacheKey, value);
        try {
            String v = CacheHelper.value2String(value);
            yhValueOperations.set(cacheKey, v, timeout, unit);
        } catch (Exception e) {
            logger.warn("Redis exception. value redis set,key {},value is {}, error msg is {}", cacheKey, value, e);
        }
    }

    /**
     * 取值
     *
     * @param cacheKey
     * @param clazz
     */
    public <T> T get(RedisKeyBuilder cacheKey, Class<T> clazz) {
        logger.debug("Enter get valueOperation redis value.key is {}", cacheKey);
        try {
            String value = yhValueOperations.get(cacheKey);
            return CacheHelper.string2Value(value, clazz);
        } catch (Exception e) {
            logger.warn("Redis exception. value redis get,key {}, error msg is {}", cacheKey, e);
        }
        return null;
    }

}