public class RedisCache {
@Autowired
public RedisTemplate redisTemplate;
public <T> ValueOperations<String, T> setCacheObject(String key, T value){
ValueOperations<String, T> operations = redisTemplate.opsForValue();
operations.set(key, value);
return operations;
}
public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit){
ValueOperations<String, T> operations = redisTemplate.opsForValue();
operations.set(key, value, timeout, timeUnit);
return operations;
}
public <T> T getCacheObject(String key){
ValueOperations<String, T> operations = redisTemplate.opsForValue();
return operations.get(key);
}
public void deleteObject(String key){
redisTemplate.delete(key);
}
public void deleteObject(Collection collection){
redisTemplate.delete(collection);
}
public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList){
ListOperations<String, T> listOperations = redisTemplate.opsForList();
if (dataList != null) {
int size = dataList.size();
for (int i = 0; i < size; i++) {
listOperations.leftPush(key, dataList.get(i));
}
}
return listOperations;
}
public <T> List<T> getCacheList(String key){
List<T> list = new ArrayList<>();
ListOperations<String, T> listOperations = redisTemplate.opsForList();
Long size = listOperations.size(key);
for (int i = 0; i < size; i++) {
list.add(listOperations.index(key, i));
}
return list;
}
public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
public <T> Set<T> getCacheSet(String key) {
Set<T> dataSet = new HashSet<T>();
BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
dataSet = operation.members();
return dataSet;
}
public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) {
HashOperations hashOperations = redisTemplate.opsForHash();
if (null != dataMap)
{
for (Map.Entry<String, T> entry : dataMap.entrySet())
{
hashOperations.put(key, entry.getKey(), entry.getValue());
}
}
return hashOperations;
}
public <T> Map<String, T> getCacheMap(String key) {
Map<String, T> map = redisTemplate.opsForHash().entries(key);
return map;
}
public Collection<String> keys(String pattern){
return redisTemplate.keys(pattern);
}
}