package com.moyu.redarmy.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public final class RedisUtil {
public static final int DEVICE_USER = 0;
public static final int DEVICE_EXPERIENCER = 1;
public static final int DEVICE_LEADER = 2;
public static final int DEVICE_CONTROL = 3;
public static final int ROOM_EXPERIENCERS = 4;
public static final int TYPE_DEVICE = 5;
@Autowired
private RedisTemplate redisTemplate;
// =============================common============================
public String generateKey(String key, int type) {
String _key = "";
switch (type) {
// case RedisUtil.DEVICE_EXPERIENCER: {
// _key="Device:" + key + ":Experiencer";
// break;
// }
// case RedisUtil.DEVICE_LEADER: {
// _key="Device:" + key + ":Leader";
_key="Device:" + key + ":Experiencer";
// break;
// }
case RedisUtil.DEVICE_CONTROL: {
_key = "Device:" + key + ":Controller";
break;
}
case RedisUtil.ROOM_EXPERIENCERS: {
_key = "Room:" + key + ":Experiencer";
break;
}
case RedisUtil.TYPE_DEVICE: {
_key="Type:"+key;
break;
}
default: {
_key = "Device:" + key + ":User";
break;
}
}
return _key;
}
/**
* 指定缓存失效时间
*
* @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 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删
RedisUtil工具类
最新推荐文章于 2024-01-10 17:03:24 发布