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

用MySQL實(shí)現(xiàn)分布式鎖,你聽過(guò)嗎?

數(shù)據(jù)庫(kù) MySQL 分布式
以前參加過(guò)一個(gè)庫(kù)存系統(tǒng),由于其業(yè)務(wù)復(fù)雜性,搞了很多個(gè)應(yīng)用來(lái)支撐。這樣的話一份庫(kù)存數(shù)據(jù)就有可能同時(shí)有多個(gè)應(yīng)用來(lái)修改庫(kù)存數(shù)據(jù)。

概述

以前參加過(guò)一個(gè)庫(kù)存系統(tǒng),由于其業(yè)務(wù)復(fù)雜性,搞了很多個(gè)應(yīng)用來(lái)支撐。這樣的話一份庫(kù)存數(shù)據(jù)就有可能同時(shí)有多個(gè)應(yīng)用來(lái)修改庫(kù)存數(shù)據(jù)。

比如說(shuō),有定時(shí)任務(wù)域xx.cron,和SystemA域和SystemB域這幾個(gè)JAVA應(yīng)用,可能同時(shí)修改同一份庫(kù)存數(shù)據(jù)。如果不做協(xié)調(diào)的話,就會(huì)有臟數(shù)據(jù)出現(xiàn)。

對(duì)于跨JAVA進(jìn)程的線程協(xié)調(diào),可以借助外部環(huán)境,例如DB或者Redis。下文介紹一下如何使用DB來(lái)實(shí)現(xiàn)分布式鎖。

[[427766]]

設(shè)計(jì)

本文設(shè)計(jì)的分布式鎖的交互方式如下:

  • 根據(jù)業(yè)務(wù)字段生成transaction_id,并線程安全的創(chuàng)建鎖資源
  • 根據(jù)transaction_id申請(qǐng)鎖
  • 釋放鎖

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

在使用synchronized關(guān)鍵字的時(shí)候,必須指定一個(gè)鎖對(duì)象。 

  1. synchronized(obj) {  

進(jìn)程內(nèi)的線程可以基于obj來(lái)實(shí)現(xiàn)同步。obj在這里可以理解為一個(gè)鎖對(duì)象。如果線程要進(jìn)入synchronized代碼塊里,必須先持有obj對(duì)象上的鎖。這種鎖是JAVA里面的內(nèi)置鎖,創(chuàng)建的過(guò)程是線程安全的。那么借助DB,如何保證創(chuàng)建鎖的過(guò)程是線程安全的呢?

可以利用DB中的UNIQUE KEY特性,一旦出現(xiàn)了重復(fù)的key,由于UNIQUE KEY的唯一性,會(huì)拋出異常的。在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 '事務(wù)id'
  4.  last_update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL COMMENT '最后更新時(shí)間'
  5.  create_time TIMESTAMP DEFAULT '0000-00-00 00:00:00' NOT NULL COMMENT '創(chuàng)建時(shí)間'
  6.  UNIQUE KEY `idx_transaction_id` (`transaction_id`) 

transaction_id是事務(wù)Id,比如說(shuō),可以用

倉(cāng)庫(kù) + 條碼 + 銷售模式

來(lái)組裝一個(gè)transaction_id,表示某倉(cāng)庫(kù)某銷售模式下的某個(gè)條碼資源。不同條碼,當(dāng)然就有不同的transaction_id。如果有兩個(gè)應(yīng)用,拿著相同的transaction_id來(lái)創(chuàng)建鎖資源的時(shí)候,只能有一個(gè)應(yīng)用創(chuàng)建成功。

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

DB連接池列表設(shè)計(jì)

在寫操作頻繁的業(yè)務(wù)系統(tǒng)中,通常會(huì)進(jìn)行分庫(kù),以降低單數(shù)據(jù)庫(kù)寫入的壓力,并提高寫操作的吞吐量。如果使用了分庫(kù),那么業(yè)務(wù)數(shù)據(jù)自然也都分配到各個(gè)數(shù)據(jù)庫(kù)上了。

在這種水平切分的多數(shù)據(jù)庫(kù)上使用DB分布式鎖,可以自定義一個(gè)DataSouce列表。并暴露一個(gè)getConnection(String transactionId)方法,按照transactionId找到對(duì)應(yīng)的Connection。

實(shí)現(xiàn)代碼如下: 

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

首先編寫一個(gè)initDataSourceList方法,并利用Spring的PostConstruct注解初始化一個(gè)DataSource 列表。相關(guān)的DB配置從db.properties讀取。 

  1. DLOCK_NUM=2 
  2.  
  3. DLOCK_USER_0="user1" 
  4. DLOCK_PASS_0="pass1" 
  5. DLOCK_INIT_SIZE_0=2 
  6. DLOCK_MAX_SIZE_0=10 
  7. DLOCK_URL_0="jdbc:mysql://localhost:3306/test1" 
  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。

接著最重要的一個(gè)實(shí)現(xiàn)getConnection(String transactionId)方法。實(shí)現(xiàn)原理很簡(jiǎn)單,獲取transactionId的hashcode,并對(duì)DataSource的長(zhǎng)度取模即可。

連接池列表設(shè)計(jì)好后,就可以實(shí)現(xiàn)往distributed_lock表插入數(shù)據(jù)了。 

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

根據(jù)transactionId鎖住線程

接下來(lái)利用DB的select for update特性來(lái)鎖住線程。當(dāng)多個(gè)線程根據(jù)相同的transactionId并發(fā)同時(shí)操作select for update的時(shí)候,只有一個(gè)線程能成功,其他線程都block住,直到select for update成功的線程使用commit操作后,block住的所有線程的其中一個(gè)線程才能開始干活。

我們?cè)谏厦娴腄istributedLock類中創(chuàng)建一個(gè)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.    } 

實(shí)現(xiàn)解鎖操作

當(dāng)線程執(zhí)行完任務(wù)后,必須手動(dòng)的執(zhí)行解鎖操作,之前被鎖住的線程才能繼續(xù)干活。在我們上面的實(shí)現(xiàn)中,其實(shí)就是獲取到當(dāng)時(shí)select for update成功的線程對(duì)應(yīng)的Connection,并實(shí)行commit操作即可。

那么如何獲取到呢?我們可以利用ThreadLocal。首先在DistributedLock類中定義

  1. private ThreadLocal threadLocalConn = new ThreadLocal<>(); 

每次調(diào)用lock方法的時(shí)候,把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.  
  29.            if (resultSet != null) { 
  30.                resultSet.close(); 
  31.            } 
  32.  
  33.            if (connection != null) { 
  34.                connection.close(); 
  35.            } 
  36.        } 
  37.    } 

這樣子,當(dāng)獲取到Connection后,將其設(shè)置到ThreadLocal中,如果lock方法出現(xiàn)異常,則將其從ThreadLocal中移除掉。

有了這幾步后,我們可以來(lái)實(shí)現(xiàn)解鎖操作了。我們?cè)贒istributedLock添加一個(gè)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.    } 

缺點(diǎn)

畢竟是利用DB來(lái)實(shí)現(xiàn)分布式鎖,對(duì)DB還是造成一定的壓力。當(dāng)時(shí)考慮使用DB做分布式的一個(gè)重要原因是,我們的應(yīng)用是后端應(yīng)用,平時(shí)流量不大的,反而關(guān)鍵的是要保證庫(kù)存數(shù)據(jù)的正確性。對(duì)于像前端庫(kù)存系統(tǒng),比如添加購(gòu)物車占用庫(kù)存等操作,最好別使用DB來(lái)實(shí)現(xiàn)分布式鎖了。

進(jìn)一步思考

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

 

責(zé)任編輯:未麗燕 來(lái)源: 今日頭條
相關(guān)推薦

2024-01-09 08:20:05

2024-07-29 09:57:47

2023-01-12 08:24:45

ZookeeperZK服務(wù)器

2019-02-26 09:51:52

分布式鎖RedisZookeeper

2022-07-06 08:01:05

數(shù)據(jù)庫(kù)分布式

2023-08-21 19:10:34

Redis分布式

2022-01-06 10:58:07

Redis數(shù)據(jù)分布式鎖

2021-10-25 10:21:59

ZK分布式鎖ZooKeeper

2024-11-28 15:11:28

2020-11-16 12:55:41

Redis分布式鎖Zookeeper

2019-07-16 09:22:10

RedisZookeeper分布式鎖

2022-03-04 09:54:04

Redis分布式鎖腳本

2019-06-19 15:40:06

分布式鎖RedisJava

2024-04-26 08:06:58

分布式系統(tǒng)

2024-10-07 10:07:31

2021-02-28 07:49:28

Zookeeper分布式

2024-04-01 05:10:00

Redis數(shù)據(jù)庫(kù)分布式鎖

2017-01-16 14:13:37

分布式數(shù)據(jù)庫(kù)

2018-04-03 16:24:34

分布式方式

2017-04-13 10:51:09

Consul分布式
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)