用 MySQL 实现一个分布式锁,这也太强了。。
共 18165字,需浏览 37分钟
·
2021-09-23 01:52
阅读本文大概需要 6 分钟。
来自:https://blog.csdn.net/linsongbin1/article/details/79444274
设计
transaction_id
,并线程安全的创建锁资源transaction_id
申请锁动态创建锁资源
synchronized
关键字的时候,必须指定一个锁对象。synchronized(obj) {
...
}
synchronized
代码块里,必须先持有obj对象上的锁。这种锁是JAVA里面的内置锁,创建的过程是线程安全的。UNIQUE KEY
特性,一旦出现了重复的key,由于UNIQUE KEY
的唯一性,会抛出异常的。SQLIntegrityConstraintViolationException
异常。create table distributed_lock
(
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '自增主键',
transaction_id varchar(128) NOT NULL DEFAULT '' COMMENT '事务id',
last_update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL COMMENT '最后更新时间',
create_time TIMESTAMP DEFAULT '0000-00-00 00:00:00' NOT NULL COMMENT '创建时间',
UNIQUE KEY `idx_transaction_id` (`transaction_id`)
)
transaction_id
是事务Id,比如说,可以用仓库 + 条码 + 销售模式
transaction_id
,表示某仓库某销售模式下的某个条码资源。不同条码,当然就有不同的transaction_id
。如果有两个应用,拿着相同的transaction_id
来创建锁资源的时候,只能有一个应用创建成功。一条 distributed_lock
记录插入成功了,就表示一份锁资源创建成功了。
DB连接池列表设计
DataSouce
列表。并暴露一个getConnection(String transactionId)
方法,按照transactionId
找到对应的Connection
。package dlock;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@Component
public class DataSourcePool {
private List<DruidDataSource> dlockDataSources = new ArrayList<>();
@PostConstruct
private void initDataSourceList() throws IOException {
Properties properties = new Properties();
FileInputStream fis = new FileInputStream("db.properties");
properties.load(fis);
Integer lockNum = Integer.valueOf(properties.getProperty("DLOCK_NUM"));
for (int i = 0; i < lockNum; i++) {
String user = properties.getProperty("DLOCK_USER_" + i);
String password = properties.getProperty("DLOCK_PASS_" + i);
Integer initSize = Integer.valueOf(properties.getProperty("DLOCK_INIT_SIZE_" + i));
Integer maxSize = Integer.valueOf(properties.getProperty("DLOCK_MAX_SIZE_" + i));
String url = properties.getProperty("DLOCK_URL_" + i);
DruidDataSource dataSource = createDataSource(user,password,initSize,maxSize,url);
dlockDataSources.add(dataSource);
}
}
private DruidDataSource createDataSource(String user, String password, Integer initSize, Integer maxSize, String url) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setInitialSize(initSize);
dataSource.setMaxActive(maxSize);
return dataSource;
}
public Connection getConnection(String transactionId) throws Exception {
if (dlockDataSources.size() <= 0) {
return null;
}
if (transactionId == null || "".equals(transactionId)) {
throw new RuntimeException("transactionId是必须的");
}
int hascode = transactionId.hashCode();
if (hascode < 0) {
hascode = - hascode;
}
return dlockDataSources.get(hascode % dlockDataSources.size()).getConnection();
}
}
initDataSourceList
方法,并利用Spring的PostConstruct
注解初始化一个DataSource
列表。相关的DB配置从db.properties
读取。DLOCK_NUM=2
DLOCK_USER_0="user1"
DLOCK_PASS_0="pass1"
DLOCK_INIT_SIZE_0=2
DLOCK_MAX_SIZE_0=10
DLOCK_URL_0="jdbc:mysql://localhost:3306/test1"
DLOCK_USER_1="user1"
DLOCK_PASS_1="pass1"
DLOCK_INIT_SIZE_1=2
DLOCK_MAX_SIZE_1=10
DLOCK_URL_1="jdbc:mysql://localhost:3306/test2"
DataSource
使用阿里的DruidDataSource
。getConnection(String transactionId)
方法。实现原理很简单,获取transactionId
的hashcode,并对DataSource
的长度取模即可。distributed_lock
表插入数据了。package dlock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.*;
@Component
public class DistributedLock {
@Autowired
private DataSourcePool dataSourcePool;
/**
* 根据transactionId创建锁资源
*/
public String createLock(String transactionId) throws Exception{
if (transactionId == null) {
throw new RuntimeException("transactionId是必须的");
}
Connection connection = null;
Statement statement = null;
try {
connection = dataSourcePool.getConnection(transactionId);
connection.setAutoCommit(false);
statement = connection.createStatement();
statement.executeUpdate("INSERT INTO distributed_lock(transaction_id) VALUES ('" + transactionId + "')");
connection.commit();
return transactionId;
}
catch (SQLIntegrityConstraintViolationException icv) {
//说明已经生成过了。
if (connection != null) {
connection.rollback();
}
return transactionId;
}
catch (Exception e) {
if (connection != null) {
connection.rollback();
}
throw e;
}
finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
}
根据transactionId锁住线程
select for update
特性来锁住线程。当多个线程根据相同的transactionId
并发同时操作select for update
的时候,只有一个线程能成功,其他线程都block
住,直到select for update
成功的线程使用commit
操作后,block
住的所有线程的其中一个线程才能开始干活。我们在上面的DistributedLock
类中创建一个lock
方法。
public boolean lock(String transactionId) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = dataSourcePool.getConnection(transactionId);
preparedStatement = connection.prepareStatement("SELECT * FROM distributed_lock WHERE transaction_id = ? FOR UPDATE ");
preparedStatement.setString(1,transactionId);
resultSet = preparedStatement.executeQuery();
if (!resultSet.next()) {
connection.rollback();
return false;
}
return true;
} catch (Exception e) {
if (connection != null) {
connection.rollback();
}
throw e;
}
finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (connection != null) {
connection.close();
}
}
}
实现解锁操作
select for update
成功的线程对应的Connection
,并实行commit
操作即可。ThreadLocal
。首先在DistributedLock
类中定义private ThreadLocal<Connection> threadLocalConn = new ThreadLocal<>();
lock
方法的时候,把Connection
放置到ThreadLocal
里面。我们修改lock
方法。
public boolean lock(String transactionId) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = dataSourcePool.getConnection(transactionId);
threadLocalConn.set(connection);
preparedStatement = connection.prepareStatement("SELECT * FROM distributed_lock WHERE transaction_id = ? FOR UPDATE ");
preparedStatement.setString(1,transactionId);
resultSet = preparedStatement.executeQuery();
if (!resultSet.next()) {
connection.rollback();
threadLocalConn.remove();
return false;
}
return true;
} catch (Exception e) {
if (connection != null) {
connection.rollback();
threadLocalConn.remove();
}
throw e;
}
finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (connection != null) {
connection.close();
}
}
}
Connection
后,将其设置到ThreadLocal
中,如果lock
方法出现异常,则将其从ThreadLocal
中移除掉。DistributedLock
添加一个unlock
方法。public void unlock() throws Exception {
Connection connection = null;
try {
connection = threadLocalConn.get();
if (!connection.isClosed()) {
connection.commit();
connection.close();
threadLocalConn.remove();
}
} catch (Exception e) {
if (connection != null) {
connection.rollback();
connection.close();
}
threadLocalConn.remove();
throw e;
}
}
缺点
进一步思考
lock
方法,写一个multiLock
方法,提供多个transactionId
的入参,for循环处理就可以了。推荐阅读:
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
朕已阅