1.使用redis中的自增来实现
2.使用setnx + del # 如果不存在set(返回1),如果存在则失败(返回0) 为了避免死锁会加上一个过期时间
自增方式
boolean isSelf = false;
try {
Long clock = cacheOperation.incrByOne(key);
if (clock.compareTo(1L) != 0) {
//没有获得锁
return;
}
isSelf = true;
finally {
if (isSelf) {
//释放锁
cacheOperation.del(key);
}
}
setnx方式
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!");
}
}