import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class RedisUtils {
private final RedisTemplate redisTemplate;
@Autowired
public RedisUtils(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public Object get(String key){
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
LOGGER.error("未设置时长普通缓存出现异常:[{}]", e);
return false;
}
}
public void del(String key){
if(redisTemplate.hasKey(key)){
redisTemplate.delete(key);
}
}
public boolean set(String key, Object value, long time){
try {
if(time > 0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
LOGGER.error("设置时长普通缓存出现异常:[{}]", e);
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
LOGGER.error("设置时长将list放入缓存出现异常:[{}]", e);
return false;
}
}
public boolean expire(String key, long time){
try {
if(time > 0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
LOGGER.error("指定缓存失效时间出现异常:[{}]", e);
return false;
}
}
}