RedisUtil工具类
RedisUtil工具类
/**
* @Auther JianHui wei -mrweijh@gmail.com
* @Create 2020/8/5 23:51
* @Versio 1.0
* @Description RedisUtil工具类
*/
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// ==========================commit==========================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 指定key 获取过期时间
*
* @param key 键 not null
* @return 时间(秒) 返回0代表永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键 not null
* @return true存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除
*
* @param key 键 not null
* @return true成功 false失败
*/
public boolean del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
return redisTemplate.delete(key[0]);
}
}
return false;
}
// ==========================String==========================
/**
* String缓存获取
*
* @param key 键 not null
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* String缓存放入
*
* @param key 键 not null
* @param value 键 not null
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* String缓存放入并设置过期时间
*
* @param key 键 not null
* @param value 值 not null
* @param time 时间(秒) time要大于0,否则不过期
* @return true成功 false失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().<