package com.shlb.timescaledbutils.utils;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.stereotype.Component;
|
|
import java.util.concurrent.TimeUnit;
|
|
@Component
|
public class RedisUtils {
|
|
@Autowired
|
private StringRedisTemplate stringRedisTemplate;
|
|
/**
|
* 写入缓存
|
*
|
* @param key 键
|
* @param value 值
|
* @return true成功 false失败
|
*/
|
public boolean set(String key, String value) {
|
try {
|
stringRedisTemplate.opsForValue().set(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 key, String value, long time) {
|
try {
|
if (time > 0) {
|
stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
|
} else {
|
set(key, value);
|
}
|
return true;
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
/**
|
* 读取缓存
|
*
|
* @param key 键
|
* @return 值
|
*/
|
public String get(String key) {
|
return key == null ? null : stringRedisTemplate.opsForValue().get(key);
|
}
|
|
/**
|
* 删除缓存
|
*
|
* @param key 键
|
*/
|
public boolean del(String key) {
|
try {
|
if (key != null && key.length() > 0) {
|
stringRedisTemplate.delete(key);
|
}
|
return true;
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
/**
|
* 指定缓存失效时间
|
*
|
* @param key 键
|
* @param time 时间(秒)
|
* @return true成功 false失败
|
*/
|
public boolean expire(String key, long time) {
|
try {
|
if (time > 0) {
|
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
|
}
|
return true;
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
|
/**
|
* 判断key是否存在
|
*
|
* @param key 键
|
* @return true 存在 false不存在
|
*/
|
public boolean hasKey(String key) {
|
try {
|
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
|
} catch (Exception e) {
|
e.printStackTrace();
|
return false;
|
}
|
}
|
}
|