RedisCacheUtils.java 1.84 KB
package com.yoho.search.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
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.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

public class RedisCacheUtils {

	public static <T> T get(YHValueOperations valueOperations, String key, Class<T> clazz) {
		RedisKeyBuilder keyBuilder = RedisKeyBuilder.newInstance().appendFixed(key);
		String compressedVal = valueOperations.get(keyBuilder);
		if (StringUtils.isBlank(compressedVal)) {
			return null;
		}
		String uncompressStr = SnappyUtils.uncompress(compressedVal);
		return unserializeFromString(uncompressStr, clazz);
	}

	public static <T> void add(YHValueOperations valueOperations, String key, T t, int expiredTimeInMinute) {
		String uncompressStr = serializeToString(t);
		String compressedVal = SnappyUtils.compress(uncompressStr);
		if (StringUtils.isBlank(compressedVal)) {
			return;
		}
		RedisKeyBuilder keyBuilder = RedisKeyBuilder.newInstance().appendFixed(key);
		valueOperations.set(keyBuilder, compressedVal, expiredTimeInMinute, TimeUnit.MINUTES);
	}
	
	public static void delete(YHRedisTemplate redisTemplate, String key) {
		redisTemplate.delete(key);
	}

	public static boolean exist(YHRedisTemplate redisTemplate, String key) {
		return redisTemplate.hasKey(key);
	}

	/**
	 * 序列化保持null值
	 * 
	 * @param t
	 * @return
	 */
	private static <T> String serializeToString(T t) {
		return JSON.toJSONString(t, SerializerFeature.WriteMapNullValue);
	}

	private static <T> T unserializeFromString(String cacheObjectValue, Class<T> clazz) {
		return JSON.parseObject(cacheObjectValue, clazz);
	}

}