用 MySQL 实现分布式锁,你听过吗?
往期热门文章: 1、全员远程办公,半年入 1 亿美元:GitHub 的最大竞争对手上市了! 2、面试官:Spring AOP、AspectJ、CGLIB 都是什么鬼?它们有什么关系? 3、10 个 VSCode 超级摸鱼神器,确定不试一下? 4、JMH + Arthas,性能监控的神器 5、MySQL 8.0 可以操作 JSON 了,牛逼 来源:blog.csdn.net/linsongbin1/article/details/79444274
概述
设计
transaction_id
,并线程安全的创建锁资源
2、根据transaction_id
申请锁
3、释放锁动态创建锁资源
synchronized
关键字的时候,必须指定一个锁对象。synchronized(obj) {
}
synchronized
代码块里,必须先持有obj对象上的锁。这种锁是JAVA里面的内置锁,创建的过程是线程安全的。那么借助DB,如何保证创建锁的过程是线程安全的呢?可以利用DB中的UNIQUE KEY
特性,一旦出现了重复的key,由于UNIQUE KEY
的唯一性,会抛出异常的。在JAVA里面,是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 ListdlockDataSources = 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 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循环处理就可以了。这个后续有时间再补上。
最近热文阅读:
1、全员远程办公,半年入 1 亿美元:GitHub 的最大竞争对手上市了! 2、面试官:Spring AOP、AspectJ、CGLIB 都是什么鬼?它们有什么关系? 3、10 个 VSCode 超级摸鱼神器,确定不试一下? 4、JMH + Arthas,性能监控的神器 5、MySQL 8.0 可以操作 JSON 了,牛逼 6、MySQL 用 limit 为什么会影响性能? 7、List中remove()方法的陷阱,被坑惨了! 8、7 种 Spring Boot 注入 Bean 的方式 9、再见MybatisPlus,阿里推出新ORM框架! 10、为什么不推荐使用BeanUtils属性转换工具 关注公众号,你想要的Java都在这里
评论