日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢(xún)
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
java分布式鎖和多線程一起使用

在Java中,分布式鎖是一種在多個(gè)JVM或多臺(tái)服務(wù)器上實(shí)現(xiàn)同步訪問(wèn)共享資源的機(jī)制,為了解決這個(gè)問(wèn)題,我們可以使用以下三種方式來(lái)實(shí)現(xiàn)分布式鎖:

專(zhuān)業(yè)從事網(wǎng)站設(shè)計(jì)制作、成都做網(wǎng)站,高端網(wǎng)站制作設(shè)計(jì),微信小程序,網(wǎng)站推廣的成都做網(wǎng)站的公司。優(yōu)秀技術(shù)團(tuán)隊(duì)竭力真誠(chéng)服務(wù),采用html5+CSS3前端渲染技術(shù),響應(yīng)式網(wǎng)站建設(shè),讓網(wǎng)站在手機(jī)、平板、PC、微信下都能呈現(xiàn)。建站過(guò)程建立專(zhuān)項(xiàng)小組,與您實(shí)時(shí)在線互動(dòng),隨時(shí)提供解決方案,暢聊想法和感受。

1、基于數(shù)據(jù)庫(kù)的分布式鎖

2、基于Redis的分布式鎖

3、基于Zookeeper的分布式鎖

接下來(lái),我們將詳細(xì)介紹這三種實(shí)現(xiàn)方式的操作方法。

基于數(shù)據(jù)庫(kù)的分布式鎖

1、創(chuàng)建一個(gè)表,用于存儲(chǔ)鎖信息。

CREATE TABLE distributed_lock (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  resource_id varchar(255) NOT NULL,
  lock_value varchar(255) NOT NULL,
  expire_time datetime NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uk_resource_id (resource_id,lock_value)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、在Java代碼中使用數(shù)據(jù)庫(kù)操作進(jìn)行加鎖和解鎖:

public class DistributedLock {
    private static final String LOCK_TABLE = "distributed_lock";
    private static final String LOCK_COLUMN = "lock_value";
    private static final String RESOURCE_ID = "resource_id";
    private static final String EXPIRE_TIME = "expire_time";
    public boolean lock() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
            String lockValue = generateLockValue(); // 生成鎖值,例如UUID
            String updateSql = "INSERT INTO " + LOCK_TABLE + "(" + RESOURCE_ID + ", " + LOCK_COLUMN + ", " + EXPIRE_TIME + ") VALUES (?, ?, NOW() + INTERVAL 30 SECOND) ON DUPLICATE KEY UPDATE " + LOCK_COLUMN + " = ?, " + EXPIRE_TIME + " = NOW() + INTERVAL 30 SECOND";
            preparedStatement = connection.prepareStatement(updateSql);
            preparedStatement.setString(1, "resource_id"); // 設(shè)置資源ID
            preparedStatement.setString(2, lockValue); // 設(shè)置鎖值
            preparedStatement.setString(3, lockValue); // 更新鎖值和過(guò)期時(shí)間
            int result = preparedStatement.executeUpdate();
            return result > 0; // 如果插入成功,則表示獲取鎖成功
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return false; // 如果獲取鎖失敗,則返回false
    }
    public void unlock() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
            String deleteSql = "DELETE FROM " + LOCK_TABLE + " WHERE " + RESOURCE_ID + " = 'resource_id' AND " + LOCK_COLUMN + " = 'lock_value'"; // 根據(jù)資源ID和鎖值刪除記錄
            preparedStatement = connection.prepareStatement(deleteSql);
            int result = preparedStatement.executeUpdate();
            if (result > 0) { // 如果刪除成功,則表示釋放鎖成功
                System.out.println("釋放鎖成功");
            } else { // 如果刪除失敗,則表示沒(méi)有獲取到鎖,無(wú)需釋放鎖
                System.out.println("沒(méi)有獲取到鎖,無(wú)需釋放鎖");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

基于Redis的分布式鎖

1、使用Redis的SETNX命令實(shí)現(xiàn)加鎖和解鎖:

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.TimeUnit;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component("distributedLock") // Spring容器中的bean名稱(chēng)為distributedLock,以便在其他類(lèi)中注入使用@Resource(name = "distributedLock") private DistributedLock distributedLock; public void doSomething() { if (distributedLock.lock()) { try { // 執(zhí)行業(yè)務(wù)邏輯 } finally { distributedLock.unlock(); } } } @Override public boolean lock() { ValueOperations valueOperations = this.redisTemplate.opsForValue(); String key = this.resourceId + this.lockValuePrefix; String lockValue = generateLockValue(); if (valueOperations.setIfAbsent(key, lockValue, this.lockExpireTime, TimeUnit.SECONDS)) { return true; } else { return false; } } @Override public void unlock() { String key = this.resourceId + this.lockValuePrefix; String lockValue = generateLockValue(); if (!StringUtils.isEmpty(lockValue)) { this.redisTemplate.delete(key); } } private String generateLockValue() { return UUID.randomUUID().toString(); } private String resourceId; private String lockValuePrefix = "lock:"; private int lockExpireTime = 30; // 默認(rèn)鎖定時(shí)間為30秒}```

分享文章:java分布式鎖和多線程一起使用
文章出自:http://www.5511xx.com/article/dpoeppg.html