Redis分布式锁的实现,redis实现分布式锁的几种方式
t;秒 int lockExpire = (int) (timeout / 1000); // 获取锁的超时时间->超过这个时间则放弃获取锁 long end = System.currentTimeMillis() + acquireTimeout; while (System.currentTimeMillis() < end) { //在获取锁时间内 if (jedis.setnx(lockKey, identifier) == 1) {//关键:设置锁 jedis.expire(lockKey, lockExpire); // 返回value值,用于释放锁时间确认 retIdentifier = identifier; return retIdentifier; } // ttl以秒为单位返回 key 的剩余过期时间,返回-1代表key没有设置超时时间,为key设置一个超时时间 if (jedis.ttl(lockKey) == -1) { jedis.expire(lockKey, lockExpire); } try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } catch (JedisException e) { e.printStackTrace(); } finally { if (jedis != null) { jedis.close(); } } return retIdentifier; } /** * 释放锁 * @param lockName 锁的key * @param identifier 释放锁的标识 * @return */ public boolean releaseLock(String lockName, String identifier) { Jedis jedis = null; String lockKey = "lock:" + lockName; boolean retFlag = false; try { jedis = jedisPool.getResource(); while (true) { // 监视lock,准备开始redis事务 jedis.watch(lockKey); // 通过前面返回的value值判断是不是该锁,若是该锁,则删除,释放锁 if (identifier.equals(jedis.get(lockKey))) { Transaction transaction = jedis.multi();//开启redis事务 transaction.del(lockKey); List<Object> results = transaction.exec();//提交redis事务 if (results == null) {//提交失败 continue;//继续循环 } retFlag = true;//提交成功 } jedis.unwatch();//解除监控 break; } } catch (JedisException e) { e.printStackTrace(); } finally { if (jedis != null) { jedis.close(); } } return retFlag; }}为了验证它,我们创建SkillService.java业务类
import lombok.extern.slf4j.Slf4j;@Slf4jpublic class SkillService { final DistributedLock lock = new DistributedLock(); public static final String LOCK_KEY = "lock_resource"; int n = 500; /** * 线程业务方法 */ public void seckill() { // 返回锁的value值,供释放锁时候进行判断 String identifier = lock.lockWithTimeout(LOCK_KEY, 5000, 1000); log.info("线程:"+Thread.currentThread().getName() + "获得了锁"); log.info("剩余数量:{}",--n); lock.releaseLock(LOCK_KEY, identifier); }}
如果找不到@Slf4j日志,在pom.xml
文件加入下面的代码:
<!--@Slf4j日志依赖组件--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId></dependency>
编辑一个测试类TestLock.java
/** * @author swadian * @date 2022/3/4 * @Version 1.0 */public class TestLock { public static void main(String[] args) { SkillService service = new SkillService(); for (int i = 10; i < 60; i++) { //开50个线程 SkillThread skillThread = new SkillThread(service, "skillThread->" + i); skillThread.start(); } }}class SkillThread extends Thread { private SkillService skillService; public SkillThread(SkillService skillService, String skillThreadName) { super(skillThreadName); this.skillService = skillService; } @Override public void run() { skillService.seckill(); }}
测试结果显示,加锁后剩余数量全部是顺序串行的,499,498,497...
我们修改SkillService.java业务类,注释掉加锁逻辑
@Slf4jpublic class SkillService { final DistributedLock lock = new DistributedLock(); public static final String LOCK_KEY = "lock_resource"; int n = 500; /** * 线程业务方法 */ public void seckill() { // 返回锁的value值,供释放锁时候进行判断 //String identifier = lock.lockWithTimeout(LOCK_KEY, 5000, 1000); log.info("线程:"+Thread.currentThread().getName() + "获得了锁"); log.info("剩余数量:{}",--n); //lock.releaseLock(LOCK_KEY, identifier); }}
重新执行测试,注释掉加锁逻辑后,剩余数量全部是乱序的,472,454,452...
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注盛行IT的更多内容!
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。