package com.njupt.swg.cache; import com.njupt.swg.exception.SnailmallException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * @Author swg. * @Date 2019/1/1 15:03 * @CONTACT 317758022@qq.com * @DESC * 该类是一个通用的缓存工具类,用于与Redis进行交互,实现缓存数据的存储、获取、设置过期时间以及删除等操作。 * 依赖Spring框架进行组件管理,并使用Jedis库来操作Redis缓存。 */ @Component @Slf4j public class CommonCacheUtil { // 通过依赖注入获取JedisPoolWrapper实例,用于后续获取JedisPool来操作Redis @Autowired private JedisPoolWrapper jedisPoolWrapper; /** * 缓存永久key * 此方法用于向Redis缓存中永久存储一个键值对,即将指定的key和value存入Redis中。 * 如果在操作过程中出现异常,会记录错误日志并抛出自定义的SnailmallException异常。 * * @param key 要存入缓存的键 * @param value 要存入缓存对应键的值 */ public void cache(String key, String value) { try { // 通过JedisPoolWrapper获取JedisPool实例,JedisPool用于管理Jedis连接资源 JedisPool pool = jedisPoolWrapper.getJedisPool(); if (pool!= null) { // 从JedisPool中获取一个Jedis连接资源,使用try-with-resources语句确保资源能自动关闭 try (Jedis Jedis = pool.getResource()) { // 选择Redis的数据库,这里选择索引为0的数据库(通常用于存放通用缓存数据等情况) Jedis.select(0); // 将键值对存入Redis Jedis.set(key, value); } } } catch (Exception e) { // 如果出现异常,记录详细的错误日志,日志内容为"redis存值失败"以及异常信息 log.error("redis存值失败", e); // 抛出自定义的SnailmallException异常,异常信息为"redis报错" throw new SnailmallException("redis报错"); } } /** * 获取缓存key * 该方法用于从Redis缓存中获取指定key对应的value值。 * 若获取过程中出现异常,同样会记录错误日志并抛出自定义异常。 * * @param key 要获取值的缓存键 * @return 返回从Redis中获取到的对应键的值,如果没获取到则返回null */ public String getCacheValue(String key) { String value = null; try { JedisPool pool = jedisPoolWrapper.getJedisPool(); if (pool!= null) { try (Jedis Jedis = pool.getResource()) { Jedis.select(0); // 从Redis中获取指定键的值 value = Jedis.get(key); } } } catch (Exception e) { log.error("redis获取指失败", e); throw new SnailmallException("redis报错"); } return value; } /** * 过期key * 此方法实现了原子性地设置缓存值(当键不存在时才设置)并设置过期时间的功能。 * 操作Redis过程中若出现异常,会记录日志并抛出自定义异常,最后返回setnx操作的结果。 * * @param key 要设置的缓存键 * @param value 要设置的缓存值 * @param expire 设置的过期时间(单位可能是秒,具体取决于Redis配置) * @return 返回jedis.setnx操作的结果,若键不存在设置成功返回1,否则返回0 */ public long cacheNxExpire(String key, String value, int expire) { long result = 0; try { JedisPool pool = jedisPoolWrapper.getJedisPool(); if (pool!= null) { try (Jedis jedis = pool.getResource()) { jedis.select(0); // 原子性地设置缓存值(当键不存在时才设置),返回设置结果 result = jedis.setnx(key, value); // 为该键设置过期时间 jedis.expire(key, expire); } } } catch (Exception e) { log.error("redis塞值和设置缓存时间失败", e); throw new SnailmallException("redis报错"); } return result; } /** * 删除缓存key * 用于从Redis中删除指定的key对应的缓存数据。 * 如果在删除过程中出现异常,会记录错误日志并抛出自定义异常。 * * @param key 要删除的缓存键 */ public void delKey(String key) { JedisPool pool = jedisPoolWrapper.getJedisPool(); if (pool!= null) { try (Jedis jedis = pool.getResource()) { jedis.select(0); try { // 调用Jedis的del方法删除指定的键 jedis.del(key); } catch (Exception e) { log.error("从redis中删除失败", e); throw new SnailmallException("redis报错"); } } } } }