利用DB实现分布式锁的思路

数据库 其他数据库 后端 分布式
以前参加过一个库存系统,由于其业务复杂性,搞了很多个应用来支撑。这样的话一份库存数据就有可能同时有多个应用来修改库存数据。比如说,有定时任务域xx.cron,和SystemA域和SystemB域这几个JAVA应用,可能同时修改同一份库存数据。如果不做协调的话,就会有脏数据出现。对于跨JAVA进程的线程协调,可以借助外部环境,例如DB或者Redis。下文介绍一下如何使用DB来实现分布式锁。

[[225288]]

概述

以前参加过一个库存系统,由于其业务复杂性,搞了很多个应用来支撑。这样的话一份库存数据就有可能同时有多个应用来修改库存数据。比如说,有定时任务域xx.cron,和SystemA域和SystemB域这几个JAVA应用,可能同时修改同一份库存数据。如果不做协调的话,就会有脏数据出现。对于跨JAVA进程的线程协调,可以借助外部环境,例如DB或者Redis。下文介绍一下如何使用DB来实现分布式锁。

设计

本文设计的分布式锁的交互方式如下:

1、根据业务字段生成transaction_id,并线程安全的创建锁资源

2、根据transaction_id申请锁

3、释放锁

动态创建锁资源

在使用synchronized关键字的时候,必须指定一个锁对象。

synchronized(obj) { }

进程内的线程可以基于obj来实现同步。obj在这里可以理解为一个锁对象。如果线程要进入synchronized代码块里,必须先持有obj对象上的锁。这种锁是JAVA里面的内置锁,创建的过程是线程安全的。那么借助DB,如何保证创建锁的过程是线程安全的呢?可以利用DB中的UNIQUE KEY特性,一旦出现了重复的key,由于UNIQUE KEY的唯一性,会抛出异常的。在JAVA里面,是SQLIntegrityConstraintViolationException异常。

 

  1. create table distributed_lock(  
  2.     id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '自增主键' 
  3.     transaction_id varchar(128) NOT NULL DEFAULT '' COMMENT '事务id' 
  4.     last_update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL COMMENT '***更新时间' 
  5.     create_time TIMESTAMP DEFAULT '0000-00-00 00:00:00' NOT NULL COMMENT '创建时间' 
  6.     UNIQUE KEY `idx_transaction_id` (`transaction_id`)  

transaction_id是事务Id,比如说,可以用

仓库 + 条码 + 销售模式

来组装一个transaction_id,表示某仓库某销售模式下的某个条码资源。不同条码,当然就有不同的transaction_id。如果有两个应用,拿着相同的transaction_id来创建锁资源的时候,只能有一个应用创建成功。

一条distributed_lock记录插入成功了,就表示一份锁资源创建成功了。

DB连接池列表设计

在写操作频繁的业务系统中,通常会进行分库,以降低单数据库写入的压力,并提高写操作的吞吐量。如果使用了分库,那么业务数据自然也都分配到各个数据库上了。在这种水平切分的多数据库上使用DB分布式锁,可以自定义一个DataSouce列表。并暴露一个getConnection(String transactionId)方法,按照transactionId找到对应的Connection。

实现代码如下:

 

  1. package dlock;   
  2. import com.alibaba.druid.pool.DruidDataSource;  
  3. import org.springframework.stereotype.Component;   
  4. import javax.annotation.PostConstruct;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7. import java.sql.Connection 
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10. import java.util.Properties;   
  11.  
  12. @Component  
  13. public class DataSourcePool {  
  14.     private List dlockDataSources = new ArrayList();   
  15.  
  16.     @PostConstruct  
  17.     private void initDataSourceList() throws IOException {  
  18.         Properties properties = new Properties();  
  19.         FileInputStream fis = new FileInputStream("db.properties");  
  20.         properties.load(fis); 
  21.  
  22.         Integer lockNum = Integer.valueOf(properties.getProperty("DLOCK_NUM"));  
  23.         for (int i = 0; i "DLOCK_USER_" + i);  
  24.             String password = properties.getProperty("DLOCK_PASS_" + i);  
  25.             Integer initSize = Integer.valueOf(properties.getProperty("DLOCK_INIT_SIZE_" + i));  
  26.             Integer maxSize = Integer.valueOf(properties.getProperty("DLOCK_MAX_SIZE_" + i));  
  27.             String url = properties.getProperty("DLOCK_URL_" + i);   
  28.  
  29.             DruidDataSource dataSource = createDataSource(user,password,initSize,maxSize,url);  
  30.             dlockDataSources.add(dataSource);  
  31.         }  
  32.     }    
  33.  
  34.     private DruidDataSource createDataSource(String user, String passwordInteger initSize, Integer maxSize, String url) {  
  35.         DruidDataSource dataSource = new DruidDataSource();  
  36.         dataSource.setDriverClassName("com.mysql.jdbc.Driver");  
  37.         dataSource.setUsername(user);  
  38.         dataSource.setPassword(password);  
  39.         dataSource.setUrl(url);  
  40.         dataSource.setInitialSize(initSize);  
  41.         dataSource.setMaxActive(maxSize);  
  42.  
  43.         return dataSource;  
  44.     } 
  45.  
  46.     public Connection getConnection(String transactionId) throws Exception { 
  47.         if (dlockDataSources.size() 0) {  
  48.             return null 
  49.         }   
  50.  
  51.         if (transactionId == null || "".equals(transactionId)) {  
  52.             throw new RuntimeException("transactionId是必须的");  
  53.         } 
  54.         int hascode = transactionId.hashCode();  
  55.         if (hascode 0) {  
  56.             hascode = - hascode;  
  57.         } 
  58.         return dlockDataSources.get(hascode % dlockDataSources.size()).getConnection();  
  59.     }  

首先编写一个initDataSourceList方法,并利用Spring的PostConstruct注解初始化一个DataSource 列表。相关的DB配置从db.properties读取。

 

  1. DLOCK_NUM=2   
  2. DLOCK_USER_0="user1"  
  3. DLOCK_PASS_0="pass1"  
  4. DLOCK_INIT_SIZE_0=2  
  5. DLOCK_MAX_SIZE_0=10  
  6. DLOCK_URL_0="jdbc:mysql://localhost:3306/test1" 
  7.   
  8.  
  9. DLOCK_USER_1="user1" 
  10. DLOCK_PASS_1="pass1"  
  11. DLOCK_INIT_SIZE_1=2  
  12. DLOCK_MAX_SIZE_1=10  
  13. DLOCK_URL_1="jdbc:mysql://localhost:3306/test2" 

DataSource使用阿里的DruidDataSource。

接着最重要的一个实现getConnection(String transactionId)方法。实现原理很简单,获取transactionId的hashcode,并对DataSource的长度取模即可。

连接池列表设计好后,就可以实现往distributed_lock表插入数据了。

 

  1. package dlock;   
  2. import org.springframework.beans.factory.annotation.Autowired;  
  3. import org.springframework.stereotype.Component;   
  4.  
  5. import java.sql.*;   
  6.  
  7. @Component  
  8. public class DistributedLock {  
  9.     @Autowired  
  10.     private DataSourcePool dataSourcePool;    
  11.  
  12.     /**  
  13.      * 根据transactionId创建锁资源  
  14.      */  
  15.     public String createLock(String transactionId) throws Exception{  
  16.         if (transactionId == null) {  
  17.             throw new RuntimeException("transactionId是必须的");  
  18.         } 
  19.         Connection connection = null 
  20.         Statement statement = null 
  21.         try {  
  22.             connection = dataSourcePool.getConnection(transactionId);  
  23.             connection.setAutoCommit(false);  
  24.             statement = connection.createStatement();  
  25.             statement.executeUpdate("INSERT INTO distributed_lock(transaction_id) VALUES ('" + transactionId + "')");  
  26.             connection.commit();  
  27.             return transactionId;  
  28.         }  
  29.         catch (SQLIntegrityConstraintViolationException icv) {  
  30.             //说明已经生成过了。  
  31.             if (connection != null) {  
  32.                 connection.rollback();  
  33.             }  
  34.             return transactionId;  
  35.         }  
  36.         catch (Exception e) {  
  37.             if (connection != null) {  
  38.                 connection.rollback();  
  39.             }  
  40.             throw  e;  
  41.         }  
  42.         finally {  
  43.             if (statement != null) {  
  44.                 statement.close();  
  45.             }  
  46.  
  47.             if (connection != null) {  
  48.                 connection.close();  
  49.             }  
  50.         }  
  51.     }  

根据transactionId锁住线程

接下来利用DB的select for update特性来锁住线程。当多个线程根据相同的transactionId并发同时操作select for update的时候,只有一个线程能成功,其他线程都block住,直到select for update成功的线程使用commit操作后,block住的所有线程的其中一个线程才能开始干活。我们在上面的DistributedLock类中创建一个lock方法。

 

  1. public boolean lock(String transactionId) throws Exception {  
  2.         Connection connection = null 
  3.         PreparedStatement preparedStatement = null 
  4.         ResultSet resultSet = null 
  5.         try {  
  6.             connection = dataSourcePool.getConnection(transactionId);  
  7.             preparedStatement = connection.prepareStatement("SELECT * FROM distributed_lock WHERE transaction_id = ? FOR UPDATE ");  
  8.             preparedStatement.setString(1,transactionId);  
  9.             resultSet = preparedStatement.executeQuery();  
  10.             if (!resultSet.next()) {  
  11.                 connection.rollback();  
  12.                 return false 
  13.             }  
  14.             return true 
  15.         } catch (Exception e) {  
  16.             if (connection != null) {  
  17.                 connection.rollback();  
  18.             }  
  19.             throw  e;  
  20.         }  
  21.         finally {  
  22.             if (preparedStatement != null) {  
  23.                 preparedStatement.close();  
  24.             }   
  25.  
  26.             if (resultSet != null) {  
  27.                 resultSet.close();  
  28.             } 
  29.  
  30.             if (connection != null) {  
  31.                 connection.close();  
  32.             }  
  33.         }  
  34.     } 

实现解锁操作

当线程执行完任务后,必须手动的执行解锁操作,之前被锁住的线程才能继续干活。在我们上面的实现中,其实就是获取到当时select for update成功的线程对应的Connection,并实行commit操作即可。

那么如何获取到呢?我们可以利用ThreadLocal。首先在DistributedLock类中定义

 

  1. private ThreadLocal threadLocalConn = new ThreadLocal(); 

每次调用lock方法的时候,把Connection放置到ThreadLocal里面。我们修改lock方法。

 

  1. public boolean lock(String transactionId) throws Exception {  
  2.         Connection connection = null 
  3.         PreparedStatement preparedStatement = null 
  4.         ResultSet resultSet = null 
  5.         try {  
  6.             connection = dataSourcePool.getConnection(transactionId);  
  7.             threadLocalConn.set(connection);  
  8.             preparedStatement = connection.prepareStatement("SELECT * FROM distributed_lock WHERE transaction_id = ? FOR UPDATE ");  
  9.             preparedStatement.setString(1,transactionId);  
  10.             resultSet = preparedStatement.executeQuery();  
  11.             if (!resultSet.next()) {  
  12.                 connection.rollback();  
  13.                 threadLocalConn.remove();  
  14.                 return false 
  15.             }  
  16.             return true 
  17.         } catch (Exception e) {  
  18.             if (connection != null) {  
  19.                 connection.rollback();  
  20.                 threadLocalConn.remove();  
  21.             }  
  22.             throw  e;  
  23.         }  
  24.         finally {  
  25.             if (preparedStatement != null) {  
  26.                 preparedStatement.close();  
  27.             }   
  28.             if (resultSet != null) {  
  29.                 resultSet.close();  
  30.             } 
  31.  
  32.             if (connection != null) {  
  33.                 connection.close();  
  34.             }  
  35.         }  
  36.     } 

这样子,当获取到Connection后,将其设置到ThreadLocal中,如果lock方法出现异常,则将其从ThreadLocal中移除掉。

有了这几步后,我们可以来实现解锁操作了。我们在DistributedLock添加一个unlock方法。

 

  1. public void unlock() throws Exception {  
  2.         Connection connection = null 
  3.         try {  
  4.             connection = threadLocalConn.get();  
  5.             if (!connection.isClosed()) {  
  6.                 connection.commit();  
  7.                 connection.close();  
  8.                 threadLocalConn.remove();  
  9.             }  
  10.         } catch (Exception e) {  
  11.             if (connection != null) {  
  12.                 connection.rollback();  
  13.                 connection.close();  
  14.             }  
  15.             threadLocalConn.remove();  
  16.             throw e;  
  17.         }  
  18.     } 

缺点

毕竟是利用DB来实现分布式锁,对DB还是造成一定的压力。当时考虑使用DB做分布式的一个重要原因是,我们的应用是后端应用,平时流量不大的,反而关键的是要保证库存数据的正确性。对于像前端库存系统,比如添加购物车占用库存等操作,***别使用DB来实现分布式锁了。

进一步思考

 

如果想锁住多份数据该怎么实现?比如说,某个库存操作,既要修改物理库存,又要修改虚拟库存,想锁住物理库存的同时,又锁住虚拟库存。其实也不是很难,参考lock方法,写一个multiLock方法,提供多个transactionId的入参,for循环处理就可以了。这个后续有时间再补上。 

责任编辑:庞桂玉 来源: 数据库开发
相关推荐

2015-05-18 09:59:48

ZooKeeper分布式计算Hadoop

2019-06-19 15:40:06

分布式锁RedisJava

2021-02-28 07:49:28

Zookeeper分布式

2017-01-16 14:13:37

分布式数据库

2018-04-03 16:24:34

分布式方式

2017-04-13 10:51:09

Consul分布式

2022-04-08 08:27:08

分布式锁系统

2019-02-26 09:51:52

分布式锁RedisZookeeper

2022-01-06 10:58:07

Redis数据分布式锁

2023-08-21 19:10:34

Redis分布式

2021-10-25 10:21:59

ZK分布式锁ZooKeeper

2023-03-01 08:07:51

2022-10-27 10:44:14

分布式Zookeeper

2023-09-13 09:52:14

分布式锁Java

2024-01-02 13:15:00

分布式锁RedissonRedis

2019-12-25 14:35:33

分布式架构系统

2023-01-13 07:39:07

2023-09-04 08:12:16

分布式锁Springboot

2023-10-11 09:37:54

Redis分布式系统

2017-10-24 11:28:23

Zookeeper分布式锁架构
点赞
收藏

51CTO技术栈公众号