Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Redlock to realize distributed Lock in springcloud

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Redlock to achieve distributed locks in springcloud". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how springcloud uses Redlock to achieve distributed locks".

A brief introduction to redlock

Distributed locking is a very useful technical means when different processes need to mutually exclusive access to shared resources. There are three attributes to consider to achieve efficient distributed locks:

Security attribute: mutually exclusive, no matter when only one client holds the lock

Efficiency attribute A: no deadlock

Efficiency attribute B: fault tolerance, as long as most redis nodes are working properly, the client side can acquire and release locks.

Redlock is an algorithm proposed by redis to implement distributed lock manager. This algorithm will be more secure and reliable than ordinary methods. For a discussion of this algorithm, take a look at the official documentation.

2. How to use java to use redlock

Introduce redis and redisson dependencies in the pom file:

Org.springframework.boot spring-boot-starter-data-redis org.redisson redisson 3.3.2

AquiredLockWorker interface class, which is mainly used to acquire the logic that needs to be handled after acquiring the lock:

/ * Created by fangzhipeng on 2017-4-5. * Logic to be processed after acquiring the lock * / public interface AquiredLockWorker {T invokeAfterLockAquire () throws Exception;}

DistributedLocker gets the lock management class:

/ * Created by fangzhipeng on 2017-4-5. * get the lock management class * / public interface DistributedLocker {/ * get the name of the lock * @ param resourceName lock * @ param worker the processing class after the lock * @ param * @ return processes the data to be returned by the specific business logic * @ throws UnableToAquireLockException * @ throws Exception * / T lock (String resourceName AquiredLockWorker worker) throws UnableToAquireLockException, Exception T lock (String resourceName, AquiredLockWorker worker, int lockTime) throws UnableToAquireLockException, Exception;}

UnableToAquireLockException, the exception class of the lock cannot be obtained:

/ * Created by fangzhipeng on 2017-4-5. * exception class * / public class UnableToAquireLockException extends RuntimeException {public UnableToAquireLockException () {} public UnableToAquireLockException (String message) {super (message);} public UnableToAquireLockException (String message, Throwable cause) {super (message, cause);}}

RedissonConnector connection class:

/ * Created by fangzhipeng on 2017-4-5. * get the RedissonClient connection class * / @ Componentpublic class RedissonConnector {RedissonClient redisson; @ PostConstruct public void init () {redisson = Redisson.create ();} public RedissonClient getClient () {return redisson;}}

The RedisLocker class, which implements 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. * / @ Componentpublic class RedisLocker implements DistributedLocker {private final static String LOCKER_PREFIX = "lock:"; @ Autowired RedissonConnector redissonConnector @ Override public T lock (String resourceName, AquiredLockWorker worker) throws InterruptedException, UnableToAquireLockException, Exception {return lock (resourceName, worker, 100);} @ Override public T lock (String resourceName, AquiredLockWorker 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 ();}}

Test class:

@ 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 () {@ 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; 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 ();}}

Run the test class:

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

In terms of running results, in the case of an asynchronous task, it is true that the thread cannot run until the lock has been acquired. In any case, this is a scheme officially recommended by redis, which is relatively reliable.

Thank you for reading, the above is the content of "how springcloud uses Redlock to achieve distributed locks". After the study of this article, I believe you have a deeper understanding of how springcloud uses Redlock to achieve distributed locks, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report