package com.guwan.backend.util; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Slf4j @Component @RequiredArgsConstructor public class RedisUtil { private final RedisTemplate redisTemplate; /** * 设置缓存 */ public void set(String key, Object value, long timeout, TimeUnit timeUnit) { try { redisTemplate.opsForValue().set(key, value, timeout, timeUnit); } catch (Exception e) { log.error("Redis set error: ", e); } } /** * 设置缓存(默认过期时间) */ public void set(String key, Object value) { set(key, value, 24, TimeUnit.HOURS); } /** * 获取缓存 */ public Object get(String key) { try { return redisTemplate.opsForValue().get(key); } catch (Exception e) { log.error("Redis get error: ", e); return null; } } /** * 删除缓存 */ public void delete(String key) { try { redisTemplate.delete(key); } catch (Exception e) { log.error("Redis delete error: ", e); } } /** * 判断key是否存在 */ public boolean hasKey(String key) { try { return Boolean.TRUE.equals(redisTemplate.hasKey(key)); } catch (Exception e) { log.error("Redis hasKey error: ", e); return false; } } /** * 设置过期时间 */ public void expire(String key, long timeout, TimeUnit timeUnit) { try { redisTemplate.expire(key, timeout, timeUnit); } catch (Exception e) { log.error("Redis expire error: ", e); } } /** * 自增操作 */ public Long increment(String key, long delta) { try { return redisTemplate.opsForValue().increment(key, delta); } catch (Exception e) { log.error("Redis increment error: ", e); return null; } } /** * Set集合操作 */ public void sAdd(String key, String... values) { try { redisTemplate.opsForSet().add(key, values); } catch (Exception e) { log.error("Redis sAdd error: ", e); } } public void setRemove(String key, Object... values) { try { redisTemplate.opsForSet().remove(key, values); } catch (Exception e) { log.error("Redis setRemove error: ", e); } } public boolean sHasKey(String key, Object value) { try { return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value)); } catch (Exception e) { log.error("Redis sHasKey error: ", e); return false; } } }