package com.fengqing.rushbuy.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
//添加数据
public void set(String key, String value){
this.stringRedisTemplate.opsForValue().set(key, value);
}
//添加数据(带超时时间)
public void setex(String key, String value, Long seconds){
this.stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}
//删除
public void delete(String key){
this.stringRedisTemplate.delete(key);
}
//判断key是否存在
public boolean hasKey(String key){
return this.stringRedisTemplate.hasKey(key);
}
//获取
public String get(String key){
return this.stringRedisTemplate.opsForValue().get(key);
}
//加锁
public boolean lock(String key, Long expire){
RedisConnection redisConnection = this.stringRedisTemplate.getConnectionFactory().getConnection();
//加锁成功设置超时时间
if(redisConnection.setNX(key.getBytes(), "fengqing".getBytes())){//加锁成功
this.stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
redisConnection.close();
return true;
} else { //加锁失败
redisConnection.close();
return false;
}
}
//解锁
public void unlock(String key){
this.stringRedisTemplate.delete(key);
}
}