There are many ways to implement distributed locks :

 1: Database mode : Who inserted the database value first , Whoever gets the lock .

 2: Cache mode

 3: zookeeper Implement distributed lock , This is recommended

 

zk Principle and process of implementing distributed lock : Temporary node + Event notification + Semaphore , The life cycle of a temporary node is delete if the connection is broken .

   zk There are four types of nodes

    1: Persistent node

    2: Temporary node

    3: Persistent sequential node

    4: Temporary sequence node .

   zk Event notification for watcher.

Implement distributed lock technological process :

  1: connect zk

  2: Create temporary node , If created successfully , Get lock , Code execution completed , Release lock ( Close zk connect ).

                                If the creation fails , It means that a service creates a node and acquires a lock , At this time, use semaphore wait .

 3: Notification of node deletion , If there's a notification that a node has been deleted , Wake up semaphore , Try to acquire the lock again .

code :

1: Lock interface
/** * ClassName: Lock * Function: Definition lock * date: 2019 year 7 month 10 day afternoon 9:44:32 * * @author
tangjiandong */ public interface Lock { void getLock(); void unlock(); }
2: Two implementations of lock :
/** * Project Name:distributed * File Name:ZookeeperAbstractLock.java *
Package Name:com.tang.service * Date:2019 year 7 month 10 day afternoon 9:52:06 * Copyright (c) 2019,
All Rights Reserved. * */ package com.tang.service; import
java.util.concurrent.CountDownLatch; import org.I0Itec.zkclient.ZkClient; /** *
ClassName: ZookeeperAbstractLock * Function: TODO ADD FUNCTION. * date:
2019 year 7 month 10 day afternoon 9:52:06 * * @author tangjiandong */ public abstract class
ZookeeperAbstractLock implements Lock { private static final String
connectAddress = "127.0.0.1:2181"; // Connection address private static final int timeOut =
5000; // Timeout protected static final String path = "/lock"; // Created node name protected
ZkClient zkClient = new ZkClient(connectAddress); // Connection establishment protected
CountDownLatch countDownLatch = null; // Semaphore counter /** * * @see
com.tang.service.Lock#getLock() */ @Override public void getLock() { // Get lock or not
if(trylock()) { System.out.println("--------- Acquire lock !"); }else { // If the lock is waiting , Continue to acquire lock ,
Otherwise, continue to wait waitLock(); // Attempt to acquire lock getLock(); } } // Get lock or not abstract boolean trylock();
// Wait for lock abstract void waitLock(); /** * Close connection , Release lock * @see
com.tang.service.Lock#unlock() */ @Override public void unlock() { if(null !=
zkClient) { zkClient.close(); System.out.println("--------- Release lock !"); } } }
 
/** * Project Name:distributed * File Name:ZookeeperDistributedLock.java *
Package Name:com.tang.service * Date:2019 year 7 month 10 day afternoon 10:10:23 * Copyright (c)
2019, All Rights Reserved. * */ package com.tang.service; import
java.util.concurrent.CountDownLatch; import
org.I0Itec.zkclient.IZkDataListener; /** * ClassName: ZookeeperDistributedLock
* Function: The realization of acquiring lock and waiting lock * date: 2019 year 7 month 10 day afternoon 10:10:23 * * @author tangjiandong
*/ public class ZookeeperDistributedLock extends ZookeeperAbstractLock{ /** *
Acquire lock * @return * @see com.tang.service.ZookeeperAbstractLock#trylock() */
@Override boolean trylock() { try { zkClient.createEphemeral(path); // Create temporary node
return true; // Get lock if created successfully } catch (Exception e) { return false; // Failed to create, no lock obtained ,
Need to wait } } /** * Wait for lock * @see com.tang.service.ZookeeperAbstractLock#waitLock() */
@Override void waitLock() { // Create listening for nodes IZkDataListener iZkDataListener = new
IZkDataListener() { // Notification of node deletion @Override public void handleDataDeleted(String
dataPath) throws Exception { if(null != countDownLatch) {
countDownLatch.countDown(); // Counter minus one , Wake up waiting } } // Notification of node changes @Override public void
handleDataChange(String dataPath, Object data) throws Exception { // TODO
Auto-generated method stub } }; // Register to listen try {
zkClient.subscribeDataChanges(path, iZkDataListener); } catch (Exception e) {
System.out.println("--------- Node registration listening exception !"); } if(zkClient.exists(path))
// If the node exists , Then wait , { countDownLatch = new CountDownLatch(1); try {
countDownLatch.await(); // Timeout can be added , Prevent deadlock caused by delayed notification //countDownLatch.await(1000,
TimeUnit.SECONDS); } catch (InterruptedException e) { // Node wait failed
System.out.println("--------- Node waiting exception !"); e.printStackTrace(); } } // Delete listening
zkClient.unsubscribeDataChanges(path, iZkDataListener); } }
 3: call
/** * Project Name:distributed * File Name:CreateNumber.java * Package
Name:com.tang.number * Date:2019��7��9�� ����8:38:45 * Copyright (c) 2019,
���쳤����Ϸֹ�˾ All Rights Reserved. * */ package com.tang.number; import
java.util.concurrent.locks.Lock; import
java.util.concurrent.locks.ReentrantLock; import
org.springframework.beans.factory.annotation.Autowired; import
org.springframework.stereotype.Service; import
com.tang.service.ZookeeperDistributedLock; /** * ClassName: CreateNumber *
Function: TODO ADD FUNCTION. * date: 2019��7��9�� ����8:38:45 * * @author
tangjiandong */ public class CreateNumber implements Runnable{ private
com.tang.service.Lock lock = new ZookeeperDistributedLock(); // Create lock /** * * @see
java.lang.Runnable#run() */ @Override public void run() { //synchronized (this)
{ lock.getLock(); try { getNumber(); } finally { lock.unlock(); } //} } public
void getNumber() { String createJjdbh = JjdbhUtils.createJjdbh(null);
System.out.println(createJjdbh); } public static void main(String[] args) { for
(int i = 0; i < 100; i++) { new Thread( new CreateNumber()).start(); } } }
 

Technology
©2019-2020 Toolsou All rights reserved,
QCustomPlot series (5)- Real time dynamic curve python To solve the problem of dictionary writing list in GDOI2019 travels Java Basics ( Bubble sort )Unity Scene loading asynchronously ( Implementation of loading interface )" Cephalosporin wine Say go and go "? DANGER ! Don't drink alcohol when taking these drugs 2021 year 1 Monthly programmer salary statistics , average 14915 element Huawei certification HCIA-AI artificial intelligence java Simple lottery algorithm , luck draw DemoNOI2019 travels