RedisLockUtil.java
package com.meeno.inner.oa.common.redis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @description: redis锁工具类
* @author: Wzq
* @create: 2020-09-09 11:34
*/
@Component
@Slf4j
public class RedisLockUtil {
private static RedisTemplate<String, Object> redisTemplate;
private static StringRedisTemplate stringRedisTemplate;
@Autowired
private void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate){
RedisLockUtil.stringRedisTemplate = stringRedisTemplate;
}
@Autowired
private void setUserMessageService(RedisTemplate<String, Object> redisTemplate){
RedisLockUtil.redisTemplate = redisTemplate;
}
/**
* 加锁
* @param key
* @param value
* @param timeout 过期时间
*/
public static boolean lock(String key, String value, Integer timeout){
Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, value,timeout, TimeUnit.SECONDS);
//Boolean b1 = redisTemplate.opsForValue().setIfAbsent(key, value,timeout, TimeUnit.SECONDS);
if(b){
return true;
}else{
log.info("lock err!");
}
return false;
}
/**
* 释放锁
* @param key
*/
public static void releaseLock(String key){
redisTemplate.delete(key);
log.info("releaseLock success!");
}
}