package com.terra.common.service; import com.terra.common.entity.all.SettingData; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis服务类 * @author WWW */ @Service public class RedisService { @Resource private RedisTemplate redisTemplate; /** * 获取Redis模板 */ public RedisTemplate getRedisTemplate() { return redisTemplate; } /** * 设置值到redis中 * * @param key 键 * @param value 值 */ public void put(String key, Object value) { redisTemplate.opsForValue().set(key, value); } /** * 设置值到redis中,并设置过期时间 * * @param key 键 * @param value 值 * @param timeout 时间 * @param unit 单位 */ public void put(String key, Object value, long timeout, TimeUnit unit) { redisTemplate.opsForValue().set(key, value, timeout, unit); } /** * 根据key获取value * * @param key 键 */ public Object get(String key) { return redisTemplate.opsForValue().get(key); } /** * 是否存在key * * @param key 键 */ public boolean hasKey(String key) { return redisTemplate.hasKey(key); } /** * 移除key * * @param key 键 */ public void delete(String key) { if (hasKey(key)) { redisTemplate.delete(key); } } /** * 清空指定键前缀 * * @param subKeyString 键前缀 */ public void clearKeys(String subKeyString) { Set keys = redisTemplate.keys(subKeyString + "*"); if (!keys.isEmpty()) { redisTemplate.delete(keys); } } /** * 清空所有 */ public void clearAll() { Set keys = redisTemplate.keys("*"); if (!keys.isEmpty()) { redisTemplate.delete(keys); } } /** * 根据Key获取List集合 */ public List getListByKey(String key) { Object obj = get(key); if (obj instanceof List) { return (List) obj; } return null; } /** * 根据Key保存数据 */ public void saveListByKey(String key, List list) { if (null != list && !list.isEmpty()) { put(key, list, SettingData.CACHE_EXPIRE, TimeUnit.MINUTES); } } /** * 根据Key保存数据 */ public void saveListByKey(String key, List list, Integer minutes) { if (null != list && !list.isEmpty()) { put(key, list, minutes, TimeUnit.MINUTES); } } }