@Component public class RedisService { @Autowired private RedisTemplate<String, String> redisTemplate; /** * 默認過時時長,單位:秒 */ public static final long DEFAULT_EXPIRE = 60 * 60 * 24; /** * 不設置過時時長 */ public static final long NOT_EXPIRE = -1; public boolean existsKey(String key) { return redisTemplate.hasKey(key); } /** * 重名名key,若是newKey已經存在,則newKey的原值被覆蓋 * * @param oldKey * @param newKey */ public void renameKey(String oldKey, String newKey) { redisTemplate.rename(oldKey, newKey); } /** * newKey不存在時才重命名 * * @param oldKey * @param newKey * @return 修改爲功返回true */ public boolean renameKeyNotExist(String oldKey, String newKey) { return redisTemplate.renameIfAbsent(oldKey, newKey); } /** * 刪除key * * @param key */ public void deleteKey(String key) { redisTemplate.delete(key); } /** * 刪除多個key * * @param keys */ public void deleteKey(String... keys) { Set<String> kSet = Stream.of(keys).map(k -> k).collect(Collectors.toSet()); redisTemplate.delete(kSet); } /** * 刪除Key的集合 * * @param keys */ public void deleteKey(Collection<String> keys) { Set<String> kSet = keys.stream().map(k -> k).collect(Collectors.toSet()); redisTemplate.delete(kSet); } /** * 設置key的生命週期 * * @param key * @param time * @param timeUnit */ public void expireKey(String key, long time, TimeUnit timeUnit) { redisTemplate.expire(key, time, timeUnit); } /** * 指定key在指定的日期過時 * * @param key * @param date */ public void expireKeyAt(String key, Date date) { redisTemplate.expireAt(key, date); } /** * 查詢key的生命週期 * * @param key * @param timeUnit * @return */ public long getKeyExpire(String key, TimeUnit timeUnit) { return redisTemplate.getExpire(key, timeUnit); } /** * 將key設置爲永久有效 * * @param key */ public void persistKey(String key) { redisTemplate.persist(key); }