欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springcloud如何用Redlock实现分布式锁

程序员文章站 2022-06-24 09:51:40
目录一、redlock简介二、怎么用java使用 redlock三、参考资料之前写过一篇文章《 》,由于自己仅仅是阅读了相关的书籍,和查阅了相关的资料,就认为那样的是可行的。那篇文章实现的大概思路是用...

之前写过一篇文章《 》,由于自己仅仅是阅读了相关的书籍,和查阅了相关的资料,就认为那样的是可行的。那篇文章实现的大概思路是用setnx命令和setex配合使用。 setnx是一个耗时操作,因为它需要查询这个键是否存在,就算redis的百万的qps,在高并发的场景下,这种操作也是有问题的。关于redis实现分布式锁,redis官方推荐使用redlock。

一、redlock简介

在不同进程需要互斥地访问共享资源时,分布式锁是一种非常有用的技术手段。实现高效的分布式锁有三个属性需要考虑:

安全属性:互斥,不管什么时候,只有一个客户端持有锁
效率属性a:不会死锁
效率属性b:容错,只要大多数redis节点能够正常工作,客户端端都能获取和释放锁。
redlock是redis官方提出的实现分布式锁管理器的算法。这个算法会比一般的普通方法更加安全可靠。关于这个算法的讨论可以看下官方文档

二、怎么用java使用 redlock

在pom文件引入redis和redisson依赖:

<!-- redis-->
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-data-redis</artifactid>
  </dependency>
  <!-- redisson-->
  <dependency>
   <groupid>org.redisson</groupid>
   <artifactid>redisson</artifactid>
   <version>3.3.2</version>
  </dependency>

aquiredlockworker接口类,,主要是用于获取锁后需要处理的逻辑:

/**
 * created by fangzhipeng on 2017/4/5.
 * 获取锁后需要处理的逻辑
 */
public interface aquiredlockworker<t> {
     t invokeafterlockaquire() throws exception;
}

distributedlocker 获取锁管理类:

/**
 * created by fangzhipeng on 2017/4/5.
 * 获取锁管理类
 */
public interface distributedlocker {

     /**
      * 获取锁
      * @param resourcename  锁的名称
      * @param worker 获取锁后的处理类
      * @param <t>
      * @return 处理完具体的业务逻辑要返回的数据
      * @throws unabletoaquirelockexception
      * @throws exception
      */
     <t> t lock(string resourcename, aquiredlockworker<t> worker) throws unabletoaquirelockexception, exception;

     <t> t lock(string resourcename, aquiredlockworker<t> worker, int locktime) throws unabletoaquirelockexception, exception;

}

unabletoaquirelockexception ,不能获取锁的异常类:

/**
 * created by fangzhipeng on 2017/4/5.
 * 异常类
 */
public class unabletoaquirelockexception extends runtimeexception {

    public unabletoaquirelockexception() {
    }

    public unabletoaquirelockexception(string message) {
        super(message);
    }

    public unabletoaquirelockexception(string message, throwable cause) {
        super(message, cause);
    }
}

 redissonconnector 连接类:

/**
 * created by fangzhipeng on 2017/4/5.
 * 获取redissonclient连接类
 */
@component
public class redissonconnector {
    redissonclient redisson;
    @postconstruct
    public void init(){
        redisson = redisson.create();
    }

    public redissonclient getclient(){
        return redisson;
    }
}

redislocker 类,实现了distributedlocker:

import org.redisson.api.rlock;
import org.redisson.api.redissonclient;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;
import java.util.concurrent.timeunit;

/**
 * created by fangzhipeng on 2017/4/5.
 */
@component
public class redislocker  implements distributedlocker{

    private final static string locker_prefix = "lock:";

    @autowired
    redissonconnector redissonconnector;
    @override
    public <t> t lock(string resourcename, aquiredlockworker<t> worker) throws interruptedexception, unabletoaquirelockexception, exception {

        return lock(resourcename, worker, 100);
    }

    @override
    public <t> t lock(string resourcename, aquiredlockworker<t> worker, int locktime) throws unabletoaquirelockexception, exception {
        redissonclient redisson= redissonconnector.getclient();
        rlock lock = redisson.getlock(locker_prefix + resourcename);
      // wait for 100 seconds seconds and automatically unlock it after locktime seconds
        boolean success = lock.trylock(100, locktime, timeunit.seconds);
        if (success) {
            try {
                return worker.invokeafterlockaquire();
            } finally {
                lock.unlock();
            }
        }
        throw new unabletoaquirelockexception();
    }
}

测试类:

  @autowired
    redislocker distributedlocker;
    @requestmapping(value = "/redlock")
    public string testredlock() throws exception{

        countdownlatch startsignal = new countdownlatch(1);
        countdownlatch donesignal = new countdownlatch(5);
        for (int i = 0; i < 5; ++i) { // create and start threads
            new thread(new worker(startsignal, donesignal)).start();
        }
        startsignal.countdown(); // let all threads proceed
        donesignal.await();
        system.out.println("all processors done. shutdown connection");
        return "redlock";
    }

     class worker implements runnable {
        private final countdownlatch startsignal;
        private final countdownlatch donesignal;

        worker(countdownlatch startsignal, countdownlatch donesignal) {
            this.startsignal = startsignal;
            this.donesignal = donesignal;
        }

        public void run() {
            try {
                startsignal.await();
                distributedlocker.lock("test",new aquiredlockworker<object>() {

                    @override
                    public object invokeafterlockaquire() {
                        dotask();
                        return null;
                    }

                });
            }catch (exception e){

            }
        }

        void dotask() {
            system.out.println(thread.currentthread().getname() + " start");
            random random = new random();
            int _int = random.nextint(200);
            system.out.println(thread.currentthread().getname() + " sleep " + _int + "millis");
            try {
                thread.sleep(_int);
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname() + " end");
            donesignal.countdown();
        }
    }

运行测试类:

thread-48 start
thread-48 sleep 99millis
thread-48 end
thread-49 start
thread-49 sleep 118millis
thread-49 end
thread-52 start
thread-52 sleep 141millis
thread-52 end
thread-50 start
thread-50 sleep 28millis
thread-50 end
thread-51 start
thread-51 sleep 145millis
thread-51 end

从运行结果上看,在异步任务的情况下,确实是获取锁之后才能运行线程。不管怎么样,这是redis官方推荐的一种方案,可靠性比较高。

三、参考资料

https://github.com/redisson/redisson

《redis官方文档》用redis构建分布式锁

a look at the java distributed in-memory data model (powered by redis)

到此这篇关于springcloud如何用redlock实现分布式锁的文章就介绍到这了,更多相关springcloud redlock分布式锁内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!