分布式锁实现原理与最佳实践核心概念分布式锁是分布式系统中用于协调多个节点访问共享资源的机制。在分布式环境下传统的单机锁如 synchronized、ReentrantLock无法跨进程工作需要使用分布式锁来保证数据一致性。分布式锁的特性互斥性同一时刻只有一个客户端持有锁高可用锁服务本身必须高可用容错性即使客户端崩溃锁也能自动释放性能获取和释放锁的操作应该快速Redis 分布式锁// Redis 分布式锁实现 Component public class RedisDistributedLock { private final StringRedisTemplate redisTemplate; private static final String LOCK_PREFIX lock:; private static final long DEFAULT_EXPIRE_TIME 30000; // 30秒 public RedisDistributedLock(StringRedisTemplate redisTemplate) { this.redisTemplate redisTemplate; } public boolean tryLock(String key) { return tryLock(key, DEFAULT_EXPIRE_TIME); } public boolean tryLock(String key, long expireTime) { String lockKey LOCK_PREFIX key; String value UUID.randomUUID().toString(); Boolean success redisTemplate.opsForValue() .setIfAbsent(lockKey, value, expireTime, TimeUnit.MILLISECONDS); return Boolean.TRUE.equals(success); } public boolean tryLock(String key, long waitTime, long expireTime) throws InterruptedException { String lockKey LOCK_PREFIX key; String value UUID.randomUUID().toString(); long startTime System.currentTimeMillis(); while (System.currentTimeMillis() - startTime waitTime) { Boolean success redisTemplate.opsForValue() .setIfAbsent(lockKey, value, expireTime, TimeUnit.MILLISECONDS); if (Boolean.TRUE.equals(success)) { return true; } Thread.sleep(100); } return false; } public void unlock(String key) { String lockKey LOCK_PREFIX key; redisTemplate.delete(lockKey); } public void unlock(String key, String value) { String lockKey LOCK_PREFIX key; redisTemplate.execute((RedisCallbackObject) connection - { byte[] keyBytes lockKey.getBytes(StandardCharsets.UTF_8); byte[] valueBytes value.getBytes(StandardCharsets.UTF_8); if (Arrays.equals(connection.get(keyBytes), valueBytes)) { connection.del(keyBytes); } return null; }); } } // 使用 Redis 分布式锁 Service public class OrderService { private final RedisDistributedLock distributedLock; private final OrderRepository orderRepository; public OrderService(RedisDistributedLock distributedLock, OrderRepository orderRepository) { this.distributedLock distributedLock; this.orderRepository orderRepository; } public Order createOrder(Long userId, Long productId) { String lockKey order:create: userId : productId; try { if (distributedLock.tryLock(lockKey, 5000, 30000)) { // 执行业务逻辑 return createOrderInternal(userId, productId); } else { throw new RuntimeException(Too many requests, please try again later); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(Lock acquisition interrupted); } finally { distributedLock.unlock(lockKey); } } private Order createOrderInternal(Long userId, Long productId) { // 检查库存、创建订单等业务逻辑 Order order new Order(); order.setUserId(userId); order.setProductId(productId); return orderRepository.save(order); } }Redlock 算法// Redlock 分布式锁实现 Component public class RedlockDistributedLock { private final ListStringRedisTemplate redisTemplates; private static final int QUORUM 3; private static final long DEFAULT_EXPIRE_TIME 30000; public RedlockDistributedLock(ListStringRedisTemplate redisTemplates) { this.redisTemplates redisTemplates; } public boolean tryLock(String key) { return tryLock(key, DEFAULT_EXPIRE_TIME); } public boolean tryLock(String key, long expireTime) { String lockKey redlock: key; String value UUID.randomUUID().toString(); int successCount 0; long startTime System.currentTimeMillis(); for (StringRedisTemplate template : redisTemplates) { try { Boolean success template.opsForValue() .setIfAbsent(lockKey, value, expireTime, TimeUnit.MILLISECONDS); if (Boolean.TRUE.equals(success)) { successCount; } } catch (Exception e) { // 忽略单个节点的故障 } } long elapsedTime System.currentTimeMillis() - startTime; long remainingTime expireTime - elapsedTime; // 满足 quorum 且剩余时间足够 return successCount QUORUM remainingTime 0; } public void unlock(String key) { String lockKey redlock: key; for (StringRedisTemplate template : redisTemplates) { try { template.delete(lockKey); } catch (Exception e) { // 忽略单个节点的故障 } } } }ZooKeeper 分布式锁// ZooKeeper 分布式锁实现 Component public class ZkDistributedLock { private final CuratorFramework client; private static final String LOCK_PATH /locks; public ZkDistributedLock(CuratorFramework client) { this.client client; ensurePathExists(); } private void ensurePathExists() { try { if (client.checkExists().forPath(LOCK_PATH) null) { client.create().creatingParentsIfNeeded().forPath(LOCK_PATH); } } catch (Exception e) { throw new RuntimeException(Failed to create lock path, e); } } public void lock(String key) throws Exception { String lockPath LOCK_PATH / key; String nodePath client.create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) .forPath(lockPath); ListString children client.getChildren().forPath(LOCK_PATH); Collections.sort(children); String currentNode nodePath.substring(LOCK_PATH.length() 1); int index children.indexOf(currentNode); while (index ! 0) { String watchPath LOCK_PATH / children.get(index - 1); CountDownLatch latch new CountDownLatch(1); Watcher watcher event - { if (event.getType() Watcher.Event.EventType.NodeDeleted) { latch.countDown(); } }; client.getData().usingWatcher(watcher).forPath(watchPath); latch.await(); children client.getChildren().forPath(LOCK_PATH); Collections.sort(children); index children.indexOf(currentNode); } } public void unlock(String key) throws Exception { String lockPath LOCK_PATH / key; ListString children client.getChildren().forPath(LOCK_PATH); for (String child : children) { if (child.startsWith(key)) { client.delete().forPath(LOCK_PATH / child); } } } } // 使用 ZooKeeper 分布式锁 Service public class InventoryService { private final ZkDistributedLock zkLock; private final InventoryRepository inventoryRepository; public InventoryService(ZkDistributedLock zkLock, InventoryRepository inventoryRepository) { this.zkLock zkLock; this.inventoryRepository inventoryRepository; } public boolean decreaseStock(Long productId, int quantity) { String lockKey inventory: productId; try { zkLock.lock(lockKey); Inventory inventory inventoryRepository.findByProductId(productId) .orElseThrow(() - new RuntimeException(Inventory not found)); if (inventory.getStock() quantity) { inventory.setStock(inventory.getStock() - quantity); inventoryRepository.save(inventory); return true; } return false; } catch (Exception e) { throw new RuntimeException(Failed to decrease stock, e); } finally { try { zkLock.unlock(lockKey); } catch (Exception e) { // 忽略解锁异常 } } } }MySQL 分布式锁// MySQL 分布式锁实现 Component public class MysqlDistributedLock { private final JdbcTemplate jdbcTemplate; public MysqlDistributedLock(JdbcTemplate jdbcTemplate) { this.jdbcTemplate jdbcTemplate; } public boolean tryLock(String key, long expireTime) { String sql INSERT INTO distributed_locks (lock_key, lock_value, expire_time) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE lock_value IF(expire_time NOW(), VALUES(lock_value), lock_value), expire_time IF(expire_time NOW(), VALUES(expire_time), expire_time) ; String value UUID.randomUUID().toString(); LocalDateTime expireTime LocalDateTime.now().plusNanos(expireTime * 1_000_000); int affectedRows jdbcTemplate.update(sql, key, value, expireTime); return affectedRows 0; } public void unlock(String key) { String sql DELETE FROM distributed_locks WHERE lock_key ?; jdbcTemplate.update(sql, key); } } // MySQL 锁表结构 // CREATE TABLE distributed_locks ( // lock_key VARCHAR(255) PRIMARY KEY, // lock_value VARCHAR(255) NOT NULL, // expire_time DATETIME NOT NULL, // created_at DATETIME DEFAULT CURRENT_TIMESTAMP // );分布式锁的优化// 带看门狗的分布式锁 Component public class WatchdogDistributedLock { private final StringRedisTemplate redisTemplate; private final ScheduledExecutorService scheduler Executors.newScheduledThreadPool(4); private static final String LOCK_PREFIX watchdog:lock:; public WatchdogDistributedLock(StringRedisTemplate redisTemplate) { this.redisTemplate redisTemplate; } public boolean tryLock(String key, long expireTime) { String lockKey LOCK_PREFIX key; String value UUID.randomUUID().toString(); Boolean success redisTemplate.opsForValue() .setIfAbsent(lockKey, value, expireTime, TimeUnit.MILLISECONDS); if (Boolean.TRUE.equals(success)) { // 启动看门狗定时续期 scheduleWatchdog(key, value, expireTime); } return Boolean.TRUE.equals(success); } private void scheduleWatchdog(String key, String value, long expireTime) { scheduler.scheduleAtFixedRate(() - { String lockKey LOCK_PREFIX key; redisTemplate.execute((RedisCallbackObject) connection - { byte[] keyBytes lockKey.getBytes(StandardCharsets.UTF_8); byte[] valueBytes value.getBytes(StandardCharsets.UTF_8); if (Arrays.equals(connection.get(keyBytes), valueBytes)) { connection.expire(keyBytes, expireTime / 1000); } return null; }); }, expireTime / 3, expireTime / 3, TimeUnit.MILLISECONDS); } public void unlock(String key) { String lockKey LOCK_PREFIX key; redisTemplate.delete(lockKey); } } // 可重入分布式锁 Component public class ReentrantDistributedLock { private final StringRedisTemplate redisTemplate; private static final String LOCK_PREFIX reentrant:lock:; private static final String COUNTER_PREFIX reentrant:counter:; public ReentrantDistributedLock(StringRedisTemplate redisTemplate) { this.redisTemplate redisTemplate; } public boolean tryLock(String key, String ownerId) { String lockKey LOCK_PREFIX key; String counterKey COUNTER_PREFIX key : ownerId; Boolean lockAcquired redisTemplate.opsForValue() .setIfAbsent(lockKey, ownerId, 30000, TimeUnit.MILLISECONDS); if (Boolean.TRUE.equals(lockAcquired)) { redisTemplate.opsForValue().set(counterKey, 1); return true; } // 检查是否是同一个持有者 String currentOwner redisTemplate.opsForValue().get(lockKey); if (ownerId.equals(currentOwner)) { redisTemplate.opsForValue().increment(counterKey); return true; } return false; } public void unlock(String key, String ownerId) { String counterKey COUNTER_PREFIX key : ownerId; String countStr redisTemplate.opsForValue().get(counterKey); if (countStr ! null) { int count Integer.parseInt(countStr); if (count 1) { redisTemplate.opsForValue().decrement(counterKey); } else { String lockKey LOCK_PREFIX key; redisTemplate.delete(lockKey); redisTemplate.delete(counterKey); } } } }最佳实践设置合理的过期时间根据业务执行时间设置过期时间使用唯一标识使用 UUID 等唯一标识作为锁的值防止误删看门狗机制对于长时间运行的任务使用看门狗自动续期异常处理确保在异常情况下也能释放锁选择合适的实现根据业务场景选择 Redis、ZooKeeper 或数据库实现监控告警监控锁的获取和释放情况设置告警优雅降级在锁获取失败时提供降级方案对比与选择特性RedisZooKeeperMySQL性能高中低可靠性中高高实现复杂度低高低适用场景高并发、短锁分布式协调、长锁低并发、简单场景总结分布式锁是分布式系统中不可或缺的组件。选择合适的分布式锁实现需要综合考虑性能、可靠性和实现复杂度。在实际应用中需要根据业务场景选择合适的方案并做好异常处理和监控。别叫我大神叫我 Alex 就好。这其实可以更优雅一点合理的分布式锁设计让系统变得更加可靠和高效。