見識下,用 MySQL 實現(xiàn)分布式鎖 !
點擊上方藍色字體,選擇“標星公眾號”
優(yōu)質(zhì)文章,第一時間送達
概述
設(shè)計
動態(tài)創(chuàng)建鎖資源
synchronized(obj)?{
}?
create?table?distributed_lock
(
?id?BIGINT?UNSIGNED?PRIMARY?KEY?AUTO_INCREMENT?COMMENT?'自增主鍵',
?transaction_id?varchar(128)?NOT?NULL?DEFAULT?''?COMMENT?'事務(wù)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?'創(chuàng)建時間',
?UNIQUE?KEY?`idx_transaction_id`?(`transaction_id`)
)
DB連接池列表設(shè)計
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?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?????????????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();
????}
}
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"
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;
????/**
?????*?根據(jù)transactionId創(chuàng)建鎖資源
?????*/
????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)?{
????????????//說明已經(jīng)生成過了。
????????????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();
????????????}
????????}
????}
}
根據(jù)transactionId鎖住線程
?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();
????????????}
????????}
????}
實現(xiàn)解鎖操作
private?ThreadLocal?threadLocalConn?=?new?ThreadLocal<>();
?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();
????????????}
????????}
????}
?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;
????????}
????}
缺點
進一步思考
? 作者?|??Sam_Deep_Thinking
來源 |??csdn.net/linsongbin1/article/details/79444274

評論
圖片
表情
