分布式锁可以通过各种方式实现,例如使用数据库、缓存、第三方服务等。以下是一种常见的基于数据库的分布式锁实现方式:
import java.sql.*;
public class DistributedLock {
// 数据库连接信息
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";
// 锁名称
private String lockName;
// 数据库连接
private Connection connection;
public DistributedLock(String lockName) {
this.lockName = lockName;
try {
// 初始化数据库连接
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
} catch (SQLException e) {
throw new RuntimeException("Failed to initialize database connection.", e);
}
}
// 获取锁
public boolean acquire() {
try {
// 开启事务
connection.setAutoCommit(false);
// 尝试在数据库中插入一条记录,记录的名称为锁名称
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO distributed_lock (lock_name) VALUES (?)");
statement.setString(1, lockName);
statement.executeUpdate();
// 提交事务
connection.commit();
return true;
} catch (SQLException e) {
// 锁已存在,获取锁失败
return false;
} finally {
try {
// 恢复自动提交
connection.setAutoCommit(true);
} catch (SQLException e) {
throw new RuntimeException("Failed to set auto-commit to true.", e);
}
}
}
// 释放锁
public void release() {
try {
// 开启事务
connection.setAutoCommit(false);
// 删除数据库中锁名称为锁名称的记录
PreparedStatement statement = connection.prepareStatement(
"DELETE FROM distributed_lock WHERE lock_name = ?");
statement.setString(1, lockName);
statement.executeUpdate();
// 提交事务
connection.commit();
} catch (SQLException e) {
throw new RuntimeException("Failed to release lock.", e);
} finally {
try {
// 恢复自动提交
connection.setAutoCommit(true);
} catch (SQLException e) {
throw new RuntimeException("Failed to set auto-commit to true.", e);
}
}
}
}
使用示例:
public class DistributedLockExample {
public static void main(String[] args) {
DistributedLock distributedLock = new DistributedLock("mylock");
try {
// 尝试获取锁
if (distributedLock.acquire()) {
// 获取锁成功,执行业务逻辑
System.out.println("Acquired lock successfully.");
// ...
} else {
// 获取锁失败,执行其他逻辑
System.out.println("Failed to acquire lock.");
// ...
}
} finally {
// 释放锁
distributedLock.release();
}
}
}
以上代码实现了一个简单的基于数据库的分布式锁。在获取锁时,通过在数据库中插入一条记录来进行加锁操作;在释放锁时,通过删除相应的记录来进行解锁操作。