com.nxyfan.framework.common.cache.CommonCacheOperator Maven / Gradle / Ivy
package com.nxyfan.framework.common.cache;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.nxyfan.framework.common.constant.CommonConstant;
import com.nxyfan.framework.common.exception.CommonException;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* 通用Redis缓存操作器
*
* @author amour
* @date 2022/6/21 16:00
**/
@Component
public class CommonCacheOperator {
@Resource
private RedisTemplate redisTemplate;
public void put(String key, Object value) {
redisTemplate.boundValueOps(CommonConstant.REDIS_KEY_PREFIX_CACHE + key).set(value);
}
public void put(String key, Object value, long timeoutSeconds) {
redisTemplate.boundValueOps(CommonConstant.REDIS_KEY_PREFIX_CACHE + key).set(value, timeoutSeconds, TimeUnit.SECONDS);
}
public Object get(String key) {
return redisTemplate.boundValueOps(CommonConstant.REDIS_KEY_PREFIX_CACHE + key).get();
}
public Object get(String key, String prefix) {
return redisTemplate.boundValueOps(prefix + key).get();
}
public void remove(String... key) {
ArrayList keys = CollectionUtil.toList(key);
List withPrefixKeys = keys.stream().map(i -> CommonConstant.REDIS_KEY_PREFIX_CACHE + i).collect(Collectors.toList());
redisTemplate.delete(withPrefixKeys);
}
public Collection getAllKeys() {
Set keys = redisTemplate.keys(CommonConstant.REDIS_KEY_PREFIX_CACHE + "*");
if (keys != null) {
// 去掉缓存key的common prefix前缀
return keys.stream().map(key -> StrUtil.removePrefix(key, CommonConstant.REDIS_KEY_PREFIX_CACHE)).collect(Collectors.toSet());
}else {
return CollectionUtil.newHashSet();
}
}
public Collection getAllKeys(String prefix) {
Set keys = redisTemplate.keys(prefix + "*");
if (keys != null) {
// 去掉缓存key的common prefix前缀
return keys.stream().map(key -> StrUtil.removePrefix(key, CommonConstant.REDIS_KEY_PREFIX_CACHE)).collect(Collectors.toSet());
}else {
return CollectionUtil.newHashSet();
}
}
public Collection