/**
-
操作redis的工具类
*/
@Component
public class RedisUtil {@Resource
private RedisTemplate<String, String> redisTemplate;@Resource
private HashOperations<String, String, T> hashOperations;@Resource
private ValueOperations<String, T> valueOptions;
// String*
/**
* 添加
*
* @param key 对应对象的key
* @param t 对象
* @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
*/
public void put(String key, T t, long expire) {
valueOptions.set(key, t, expire, TimeUnit.SECONDS);
}
// Hash*
/**
* 添加
*
* @param Key 对应Hash的key
* @param keyForHash Hash中的key
* @param t 存储对象
* @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
*/
public void put(String Key, String keyForHash, T t, long expire) {
hashOperations.put(Key, keyForHash, t);
if (expire != -1) {
redisTemplate.expire(Key, expire, TimeUnit.SECONDS);
}
}
/**
* 查询
*
* @param Key 对应对象的key
* @param keyFroHash Hash中的key
* @return
*/
public T get(String Key, String keyFroHash) {
return hashOperations.get(Key, keyFroHash);
}
/**
* 获取当前redis库下所有对象
*
* @param Key 对应对象的key
* @return
*/
public List<T> getAll(String Key) {
return hashOperations.values(Key);
}
/**
* 查询查询当前redis库下所有key
*
* @param Key 对应对象的key
* @return
*/
public Set<String> getKeys(String Key) {
return hashOperations.keys(Key);
}
/**
* 判断key是否存在redis中
*
* @param Key 对应对象的key
* @param key Hash中对应的key
* @return
*/
public boolean isKeyExists(String Key, String key) {
return hashOperations.hasKey(Key, key);
}
/**
* 查询当前key下缓存数量
*
* @param Key 对应对象的key
* @return
*/
public long count(String Key) {
return hashOperations.size(Key);
}
// 通用*
/**
* 查询
*
* @param key 对应对象的key
* @return
*/
public T get(String key) {
return valueOptions.get(key);
}
/**
* 删除
*
* @param key 传入key的名称
*/
public void remove(String key) {
valueOptions.getOperations().delete(key);
}
/**
* 清空redis
*/
public void empty(String Key) {
Set<String> set = hashOperations.keys(Key);
for (String subKey : set) {
hashOperations.delete(Key, subKey);
}
}
}