自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

利用DB實現分布式鎖的思路

數據庫 其他數據庫 后端 分布式
以前參加過一個庫存系統(tǒng),由于其業(yè)務復雜性,搞了很多個應用來支撐。這樣的話一份庫存數據就有可能同時有多個應用來修改庫存數據。比如說,有定時任務域xx.cron,和SystemA域和SystemB域這幾個JAVA應用,可能同時修改同一份庫存數據。如果不做協調的話,就會有臟數據出現。對于跨JAVA進程的線程協調,可以借助外部環(huán)境,例如DB或者Redis。下文介紹一下如何使用DB來實現分布式鎖。

[[225288]]

概述

以前參加過一個庫存系統(tǒng),由于其業(yè)務復雜性,搞了很多個應用來支撐。這樣的話一份庫存數據就有可能同時有多個應用來修改庫存數據。比如說,有定時任務域xx.cron,和SystemA域和SystemB域這幾個JAVA應用,可能同時修改同一份庫存數據。如果不做協調的話,就會有臟數據出現。對于跨JAVA進程的線程協調,可以借助外部環(huán)境,例如DB或者Redis。下文介紹一下如何使用DB來實現分布式鎖。

設計

本文設計的分布式鎖的交互方式如下:

1、根據業(yè)務字段生成transaction_id,并線程安全的創(chuàng)建鎖資源

2、根據transaction_id申請鎖

3、釋放鎖

動態(tài)創(chuàng)建鎖資源

在使用synchronized關鍵字的時候,必須指定一個鎖對象。

synchronized(obj) { }

進程內的線程可以基于obj來實現同步。obj在這里可以理解為一個鎖對象。如果線程要進入synchronized代碼塊里,必須先持有obj對象上的鎖。這種鎖是JAVA里面的內置鎖,創(chuàng)建的過程是線程安全的。那么借助DB,如何保證創(chuàng)建鎖的過程是線程安全的呢?可以利用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 '創(chuàng)建時間' 
  6.     UNIQUE KEY `idx_transaction_id` (`transaction_id`)  

transaction_id是事務Id,比如說,可以用

倉庫 + 條碼 + 銷售模式

來組裝一個transaction_id,表示某倉庫某銷售模式下的某個條碼資源。不同條碼,當然就有不同的transaction_id。如果有兩個應用,拿著相同的transaction_id來創(chuàng)建鎖資源的時候,只能有一個應用創(chuàng)建成功。

一條distributed_lock記錄插入成功了,就表示一份鎖資源創(chuàng)建成功了。

DB連接池列表設計

在寫操作頻繁的業(yè)務系統(tǒng)中,通常會進行分庫,以降低單數據庫寫入的壓力,并提高寫操作的吞吐量。如果使用了分庫,那么業(yè)務數據自然也都分配到各個數據庫上了。在這種水平切分的多數據庫上使用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創(chuàng)建鎖資源  
  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并發(fā)同時操作select for update的時候,只有一個線程能成功,其他線程都block住,直到select for update成功的線程使用commit操作后,block住的所有線程的其中一個線程才能開始干活。我們在上面的DistributedLock類中創(chuàng)建一個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.     } 

實現解鎖操作

當線程執(zhí)行完任務后,必須手動的執(zhí)行解鎖操作,之前被鎖住的線程才能繼續(xù)干活。在我們上面的實現中,其實就是獲取到當時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做分布式的一個重要原因是,我們的應用是后端應用,平時流量不大的,反而關鍵的是要保證庫存數據的正確性。對于像前端庫存系統(tǒng),比如添加購物車占用庫存等操作,***別使用DB來實現分布式鎖了。

進一步思考

 

如果想鎖住多份數據該怎么實現?比如說,某個庫存操作,既要修改物理庫存,又要修改虛擬庫存,想鎖住物理庫存的同時,又鎖住虛擬庫存。其實也不是很難,參考lock方法,寫一個multiLock方法,提供多個transactionId的入參,for循環(huán)處理就可以了。這個后續(xù)有時間再補上。 

責任編輯:龐桂玉 來源: 數據庫開發(fā)
相關推薦

2015-05-18 09:59:48

ZooKeeper分布式計算Hadoop

2024-11-28 15:11:28

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

分布式鎖系統(tǒng)

2019-02-26 09:51:52

分布式鎖RedisZookeeper

2023-08-21 19:10:34

Redis分布式

2022-01-06 10:58:07

Redis數據分布式鎖

2021-10-25 10:21:59

ZK分布式鎖ZooKeeper

2024-10-09 17:12:34

2023-03-01 08:07:51

2023-09-13 09:52:14

分布式鎖Java

2022-10-27 10:44:14

分布式Zookeeper

2024-10-07 10:07:31

2024-07-29 09:57:47

2024-04-01 05:10:00

Redis數據庫分布式鎖

2024-01-02 13:15:00

分布式鎖RedissonRedis
點贊
收藏

51CTO技術棧公眾號