com.rustknife.jknife.cache.CacheRedisContext Maven / Gradle / Ivy
The newest version!
package com.rustknife.jknife.cache;
import com.rustknife.jknife.cache.config.SpringContextAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
@SuppressWarnings({"DuplicatedCode", "unchecked", "ConstantConditions"})
public class CacheRedisContext {
private RedisTemplate redisTemplate = null;
private boolean usePrefix = true;
private DefaultRedisCachePrefix cachePrefix = new DefaultRedisCachePrefix();
private String redisTemplateName;
public CacheRedisContext(String redisTemplateName) {
this.redisTemplateName = redisTemplateName;
}
public RedisTemplate getRedisTemplate() {
if(this.redisTemplate == null)
this.redisTemplate = SpringContextAccessor.getBean(this.redisTemplateName);
return redisTemplate;
}
public byte [] getRawKey(String cacheName, String key){
byte []rawKey = getRedisTemplate().getStringSerializer().serialize(key);
if (!usePrefix || cacheName == null || cacheName.isEmpty())
return rawKey;
byte []prefix = cachePrefix.prefix(cacheName);
byte[] prefixedKey = Arrays.copyOf(prefix, prefix.length + rawKey.length);
System.arraycopy(rawKey, 0, prefixedKey, prefix.length, rawKey.length);
return prefixedKey;
}
public void flushAll(){
getRedisTemplate().execute(connection -> {
connection.flushAll();
return null;
}, true);
}
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String cacheName, String key, long time){
try {
if(time>0){
getRedisTemplate().expire(getRawKey(cacheName, key), time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long ttl(String cacheName, String key){
return getRedisTemplate().getExpire(getRawKey(cacheName, key),TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String cacheName, String key){
try {
return getRedisTemplate().hasKey(getRawKey(cacheName, key));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 模糊查找 key 列表,同 keys 命令
* @param cacheName cacheName
* @param pattern 通配串, 默认为 *
* @return Set
*/
public Set keys(String cacheName, String pattern){
Set keysRaw = keysRaw(cacheName, pattern);
if(keysRaw == null || keysRaw.size() <= 0)
return new HashSet<>();
HashSet keys = new HashSet<>();
for(byte[] keyRaw: keysRaw)
keys.add((String) getRedisTemplate().getStringSerializer().deserialize(keyRaw));
return keys;
}
/**
* 模糊查找 raw key 列表
* @param cacheName cacheName
* @param pattern 通配串, 默认为 *
* @return Set
*/
public Set keysRaw(String cacheName, String pattern){
if(pattern == null || pattern.isEmpty())
pattern = "*";
if(cacheName != null && !cacheName.isEmpty())
pattern = cacheName + pattern;
return getRedisTemplate().keys(getRawKey(null, pattern));
}
/**
* 删除缓存
* @param keys 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String cacheName, String ... keys){
if(keys == null || keys.length <= 0)
return ;
if(keys.length==1){
getRedisTemplate().delete(getRawKey(cacheName, keys[0]));
return ;
}
List rawKeys = new LinkedList<>();
for(String v:keys) {
rawKeys.add(getRawKey(cacheName, v));
}
getRedisTemplate().delete(rawKeys);
}
/**
* 删除缓存列表
* @param keys 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String cacheName, Set keys){
if(keys == null || keys.isEmpty())
return ;
if(keys.size() == 1) {
getRedisTemplate().delete(getRawKey(cacheName, keys.iterator().next()));
return;
}
List rawKeys = new LinkedList<>();
for(String v:keys) {
rawKeys.add(getRawKey(cacheName, v));
}
getRedisTemplate().delete(rawKeys);
}
/**
* 按原始 key 删除缓存
* @param keys 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void delByRowKeys(String ... keys){
if(keys == null || keys.length <= 0)
return ;
if(keys.length == 1) {
getRedisTemplate().delete(keys[0]);
return;
}
getRedisTemplate().delete(CollectionUtils.arrayToList(keys));
}
/**
* 删除缓存列表
* @param keys 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void delByRowKeys(Set keys){
if(keys == null || keys.isEmpty())
return ;
if(keys.size() == 1) {
getRedisTemplate().delete(keys.iterator().next());
return;
}
getRedisTemplate().delete(keys);
}
//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public T get(String cacheName, String key){
if(key == null)
return null;
ValueOperations vo = getRedisTemplate().opsForValue();
return vo.get(getRawKey(cacheName, key));
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String cacheName, String key,Object value) {
try {
getRedisTemplate().opsForValue().set(getRawKey(cacheName, key), value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String cacheName, String key,Object value,long time){
try {
if(time>0){
getRedisTemplate().opsForValue().set(getRawKey(cacheName, key), value, time, TimeUnit.SECONDS);
}else{
set(cacheName, key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String cacheName, String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return getRedisTemplate().opsForValue().increment(getRawKey(cacheName, key), delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String cacheName, String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return getRedisTemplate().opsForValue().increment(getRawKey(cacheName, key), -delta);
}
/**
* 递增
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public double incr(String cacheName, String key, double delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return getRedisTemplate().opsForValue().increment(getRawKey(cacheName, key), delta);
}
/**
* 递减
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public double decr(String cacheName, String key, double delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return getRedisTemplate().opsForValue().increment(getRawKey(cacheName, key), -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String cacheName, String key,String item){
return getRedisTemplate().opsForHash().get(getRawKey(cacheName, key), item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map
© 2015 - 2025 Weber Informatics LLC | Privacy Policy