package com.dsh.utils; import com.dsh.upms.model.vo.LoginUserVo; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.util.Assert; import java.util.concurrent.TimeUnit; /** * * @author: lihong . * * @email: 765907456@qq.com . * * @createTime: 19-7-15 下午3:06 . * * description: 缓存工具类. **/ public final class CacheUtils { /** * 时间单位. */ public enum CacheTimeUnit { /** * 纳秒 */ NANOSECONDS, /** * 微秒 */ MICROSECONDS, /** * 毫秒 */ MILLISECONDS, /** * 秒 */ SECONDS, /** * 分钟 */ MINUTES, /** * 小时 */ HOURS, /** * 天 */ DAYS; /** * 单位转换. * * @return */ public TimeUnit convert() { switch (this.ordinal()) { case 0: return TimeUnit.NANOSECONDS; case 1: return TimeUnit.MICROSECONDS; case 2: return TimeUnit.MILLISECONDS; case 3: return TimeUnit.SECONDS; case 4: return TimeUnit.MINUTES; case 5: return TimeUnit.HOURS; case 6: return TimeUnit.DAYS; } return null; } } /** * 添加缓存. * * @param key * @param value */ public static void put(String key, Object value) { Assert.hasText(key, "缓存名称不能为空."); Assert.notNull(value, "缓存值不能为空"); CacheUtils.getValueOperations().set(key, value); } /** * 添加缓存,带过期时间 * * @param key * @param value * @param expire */ public static void put(String key, Object value, long expire) { Assert.hasText(key, "缓存名称不能为空."); Assert.notNull(value, "缓存值不能为空."); Assert.state(expire > 0, "缓存时间不能小于或者等于0"); CacheUtils.getValueOperations().set(key, value, expire); } /** * 添加缓存,带过期时间且设置缓存时间单位 * * @param key * @param value * @param expire * @param cacheTimeUnit */ public static void put(String key, Object value, long expire, CacheTimeUnit cacheTimeUnit) { Assert.hasText(key, "缓存名称不能为空."); Assert.notNull(value, "缓存值不能为空."); Assert.state(expire > 0, "缓存时间不能小于或者等于0"); Assert.notNull(cacheTimeUnit, "缓存时间单位不能为空."); CacheUtils.getValueOperations().set(key, value, expire, cacheTimeUnit.convert()); } /** * 根据缓存名称查询缓存是否存在. * * @param key * @return */ public static boolean exist(String key) { return getRedisTemplate().hasKey(key); } /** * 批量删除缓存. * * @param keys */ public static void delete(String... keys) { Assert.noNullElements(keys, "缓存名称不能为空."); for (String key : keys) { CacheUtils.getRedisTemplate().delete(key); } } /** * 根据key值获取缓存. * * @param key * @param * @return */ public static T get(String key) { Assert.hasText(key, "缓存名称不能为空."); Object o = CacheUtils.getValueOperations().get(key); if (o != null) { return (T) o; } return null; } /** * 获取redis模板 * * @return */ public static RedisTemplate getRedisTemplate() { RedisTemplate redisTemplate = SpringBeanUtils.getBean("redisTemplate", RedisTemplate.class); return redisTemplate; } private static ValueOperations getValueOperations() { RedisTemplate redisTemplate = CacheUtils.getRedisTemplate(); ValueOperations valueOperations = redisTemplate.opsForValue(); return valueOperations; } }