-
分布式锁原子性操作,基于springdataredis开箱即用
-
效果
-
controller
package com.sunyw.xyz.controller;
import com.sunyw.xyz.utils.Lock;
import com.sunyw.xyz.utils.LockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@Slf4j
public class RedisController {
@Autowired
private StringRedisTemplate RedisTemplate;
@Autowired
private LockUtils lockUtils;
@RequestMapping("/lock")
public String lock() {
try {
Lock lock = new Lock("order", "date");
boolean aBoolean = lockUtils.tryLock(lock, 30);
log.info("线程[{}]加锁状态为:[{}]", Thread.currentThread().getName(), aBoolean);
if (aBoolean) {
Thread.sleep(1000);
return "success";
} else {
return "wait";
}
} catch (Exception e) {
e.getMessage();
} finally {
log.info("线程[{}]释放锁", Thread.currentThread().getName());
lockUtils.unLock("order");
}
return "";
}
}
- 工具类实体
package com.sunyw.xyz.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Lock {
private String lockName;
private String lockValue;
}
- 工具类
package com.sunyw.xyz.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;
@Slf4j
public class LockUtils {
@Autowired
private StringRedisTemplate redisLock;
/**
* 加锁
*
* @param lock
* @param time 单位s
* @return
*/
public boolean tryLock(Lock lock, long time) {
return redisLock.opsForValue().setIfAbsent(lock.getLockName(), lock.getLockValue(), time, TimeUnit.SECONDS);
}
/**
* 解锁
* @param key
*/
public void unLock(String key) {
redisLock.delete(key);
}
}