1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
   | @Slf4j public class ZkLock {
      public static final String LOCK_LOG = "获取分布式锁, lock=[{}]";     private final ZooKeeper zookeeper;
      public ZkLock(ZooKeeper zookeeper) {         this.zookeeper = zookeeper;     }
 
      private void acquireDistributedLock(Long companyId, Long groupId) {         String path = getLockPath(companyId, groupId);         acquireDistributedLock(path);     }
      public void acquireDistributedLock(String path) {         try {             zookeeper.create(path, "".getBytes(),                     ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);             log.info(LOCK_LOG, path);         } catch (Exception e) {             int count = 0;             while(true) {                 try {                     Thread.sleep(1000);                     zookeeper.create(path, "".getBytes(),                             ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);                 } catch (Exception e2) {                     count++;                     log.info("尝试获取[{}]次锁, path=[{}]", count, path);                     continue;                 }                 log.info("重试[{}]次后获取到锁, path=[{}]", count, path);                 break;             }         }     }
      public boolean acquireFastFailedDistributedLock(Long companyId, Long groupId) {         String path = getLockPath(companyId, groupId);         try {             zookeeper.create(path, "".getBytes(),                     ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);             log.info(LOCK_LOG, path);             return true;         } catch (Exception e) {             log.info("获取分布式锁失败, lock=[{}]", path);         }         return false;     }
      private void releaseDistributedLock(Long companyId, Long groupId) {         String path = getLockPath(companyId, groupId);         releaseDistributedLock(path);     }
      public void releaseDistributedLock(String path) {         try {             zookeeper.delete(path, -1);             log.info("释放分布式锁, path=[{}]", path);         } catch (Exception e) {             e.printStackTrace();         }     }
      private String getLockPath(Long companyId, Long groupId) {        return  String.format(ZK_EXCLUSIVE_LOCK_INNER, companyId, groupId);     } }
   |