package com.sinata.zuul.util;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.stereotype.Component;
|
import org.springframework.util.StringUtils;
|
import java.util.UUID;
|
import java.util.concurrent.TimeUnit;
|
|
|
/**
|
* Redis工具类
|
*/
|
@Component
|
public class RedisUtil {
|
|
@Autowired
|
private RedisTemplate redisTemplate;
|
|
|
|
/**
|
* 向redis中存储字符串没有过期时间
|
* @param key
|
* @param value
|
*/
|
public void setStrValue(String key, String value){
|
if(!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)){
|
redisTemplate.opsForValue().set(key, value);
|
}
|
}
|
|
|
/**
|
* 以分钟为单位设置存储值(设置过期时间)
|
* @param key
|
* @param value
|
* @param time 秒
|
*/
|
public void setStrValue(String key, String value, int time){
|
if(!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)){
|
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
|
}
|
}
|
|
|
/**
|
* 从redis中获取值
|
* @param key
|
* @return
|
*/
|
public String getValue(String key){
|
if(!StringUtils.isEmpty(key)){
|
String data = (String) redisTemplate.opsForValue().get(key);
|
return data;
|
}
|
return null;
|
}
|
|
|
|
|
/**
|
* 删除key
|
* @param key
|
*/
|
public void remove(String key){
|
if(!StringUtils.isEmpty(key)){
|
redisTemplate.delete(key);
|
}
|
}
|
|
|
|
|
|
|
|
/**
|
* redis加锁
|
* @param key
|
* @param value
|
* @param time
|
* @return
|
*/
|
public boolean lock(String key, String value, int time){
|
if(!StringUtils.isEmpty(key)){
|
key += "_lock";
|
return redisTemplate.opsForValue().setIfAbsent(key, value);
|
}
|
return false;
|
}
|
|
/**
|
* 获取redis锁
|
* @param time
|
* @return
|
*/
|
public boolean lock(int time){
|
String uuid = UUID.randomUUID().toString();
|
return lock("redis", uuid, time);
|
}
|
|
|
public boolean lock(String key, int time){
|
String uuid = UUID.randomUUID().toString();
|
return lock(key, uuid, time);
|
}
|
|
|
/**
|
* redis释放锁
|
* @param key
|
* @return
|
*/
|
public boolean unlock(String key){
|
if(!StringUtils.isEmpty(key)){
|
key += "_lock";
|
return redisTemplate.delete(key);
|
}
|
return false;
|
}
|
|
/**
|
* 删除锁
|
* @return
|
*/
|
public boolean unlock(){
|
return unlock("redis");
|
}
|
}
|