分布式锁工具类
#LockUtil.java
package com.xy.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.UUID;
/**
* @version 1.0
* @user xy
* @date 2019/6/5 17:31
*/
@Component
public class LockUtil {
@Autowired
private RedisTemplate redisTemplate;
//redis的原始连接对象
private RedisConnection connection;
//加锁的脚本签名
private String lockLuaSha;
//添加分布式锁的lua脚本
private String lockLua = "--获得锁的名称、值、超时时间\n" +
"local lockName = KEYS[1]\n" +
"local lockValue = ARGV[1]\n" +
"local timeout = ARGV[2]\n" +
"\n" +
"--尝试进行加锁的操作\n" +
"local flag = redis.call('setnx', lockName, lockValue)\n" +
"\n" +
"--进行判断\n" +
"if flag == 1 then\n" +
"\t--说明拿到分布式锁,设置超时时间\n" +
"\tredis.call('expire', lockName, timeout)\n" +
"\t--返回成功的标识\n" +
"\treturn 1\n" +
"end\n" +
"\n" +
"--获得锁失败\n" +
"return 0";
private String unLockLuaSha;
private String unLockLua = "--获得删除锁的名称以及value值\n" +
"local lockName = KEYS[1]\n" +
"local lockValue = ARGV[1]\n" +
"\n" +
"--进行判断\n" +
"local rValue = redis.call(\"get\", lockName)\n" +
"if rValue == lockValue then\n" +
" --说明锁就是本人加的,直接删除\n" +
" redis.call('del', lockName)\n" +
" --返回状态\n" +
" return 1\n" +
"end\n" +
"\n" +
"--说明锁不是我添加的\n" +
"return 0";
private ThreadLocal<String> value = new ThreadLocal<>();
/**
* @PostConstruct - 添加的方法会在当前类的构造方法之后,并且在注入了成员变量之后执行
*
* applicationContext.xml
* <bean id="myBean" class="com.xy.xxx.xxx.Abc" init-method="init">
* </bean>
*/
@PostConstruct
private void init(){
connection = redisTemplate.getConnectionFactory().getConnection();
//缓存lua脚本
lockLuaSha = connection.scriptLoad(lockLua.getBytes());
unLockLuaSha = connection.scriptLoad(unLockLua.getBytes());
}
/**
* 上锁的方法
* @return
*/
public boolean lock(String name, long timeout){
String uuid = UUID.randomUUID().toString();
value.set(uuid);
//使用脚本加锁
Long flag = connection.evalSha(lockLuaSha, ReturnType.INTEGER,
1, name.getBytes(), uuid.getBytes(), (timeout + "").getBytes());
return flag == 1;
}
/**
* 解锁的方法
* @return
*/
public boolean unLock(String name){
String uuid = value.get();
Long result = connection.evalSha(unLockLuaSha, ReturnType.INTEGER, 1,
name.getBytes(), uuid.getBytes());
return result == 1;
}
// public static void main(String[] args) {
// ThreadLocal<String> threadLocal = new ThreadLocal<>();
// threadLocal.set("Hello!");
//
// new Thread(){
// @Override
// public void run() {
// threadLocal.set("World!");
// System.out.println(threadLocal.get());
// }
// }.start();
//
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// System.out.println(threadLocal.get());
// }
}
锁的测试
#SpringbootLockDemoApplication.java
package com.xy.springboot_redis_demo;
import com.xy.util.LockUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @version 1.0
* @user xy
* @date 2019/6/5 16:35
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootLockDemoApplication {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private LockUtil lockUtil;
@Test
public void test(){
for(int i = 0; i < 3; i++){
new Thread(){
@Override
public void run() {
//模拟多个客户端同时访问一个核心业务方法
coreService();
}
}.start();
}
while(true){
}
}
/**
* 模拟一个核心业务方法
*/
public void coreService(){
//使用脚本加锁
boolean flag = lockUtil.lock("coreserver", 6000);
//判断
if(flag){
System.out.println(Thread.currentThread().getName() + "获得分布式锁!!!");
//获得分布式锁
System.out.println(Thread.currentThread().getName() + "核心业务方法!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//释放分布式锁
System.out.println(Thread.currentThread().getName() + "释放分布式锁!!!");
lockUtil.unLock("coreserver");
} else {
//没有拿到分布式锁
//自旋
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//再次调用本身
coreService();
}
}
}
总结
分布式锁这个概念总的来说关键点是保持释放锁的原子性,还有超时的处理等。如果小伙伴觉得好用的话欢迎点个赞留个言~