package com.ddkjt.utils;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类
*/
@Component
@Slf4j
@AllArgsConstructor
public class RedisUtils {
private final RedisTemplate<String, Object> redisTemplate;
/**
* 存放object
*
* @param key 键
* @param value 值
* @param timeout 过期时间
*/
public void set(String key, Object value, Long timeout) {
try {
redisTemplate.opsForValue().set(key, toJson(value));
if (timeout != null) {
redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
} catch (Exception e) {
log.error(String.valueOf(e));
}
}
public void set(String key, Object value) {
set(key, value, null);
}
/**
* 删除
*
* @param key 键
* @return 返回boolean
*/
public Boolean delKey(String key) {
return redisTemplate.delete(key);
}
/**
* 查询
*
* @param key 键
* @return 返回Object
*/
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 判断 key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* Object转成JSON数据
*
* @param object 接收值
* @return 返回值
*/
private String toJson(Object object) {
if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double
|| object instanceof Boolean || object instanceof String) {
return String.valueOf(object);
}
return JSON.toJSONString(object);
}
}
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=345vh24dw86cw