ivanomatteo / laravel-db-mutex

请在此处填写您的包描述

0.1.9 2020-12-29 10:17 UTC

This package is auto-updated.

Last update: 2024-09-25 19:22:02 UTC


README

Software License Travis Total Downloads

此库实现了一个互斥锁机制,使用多态的“一对多”关系。

调用usingDbMutex()时,如果尚不存在,将在db_mutexes表中添加一行,匹配当前模型类型、id和指定的“名称”字段(默认名称为“default”)。

在这行上应用“锁定更新”(使用的数据库引擎必须支持它),确保互斥。

这样,您可以避免在包含您的数据的表上放置锁(可能的瓶颈),同时保留对不需要互斥的所有请求的读写能力。

安装

composer require ivanomatteo/laravel-db-mutex

php artisan migrate

使用方法

简要说明此包的使用方法。

// add HasDbMutex trait to your model

use HasDbMutex; // ( IvanoMatteo\LaravelDbMutex\HasDbMutex )


$m = YourModel::find(1);

$m->usingDbMutex(function(){ 
    // this code will run in mutual exclusion 
    // for all request calling it 
    // on the record with id 1
    sleep(5); 
    echo "done!";  
});


$m->usingDbMutex(function(){ 
    // this code will run in mutual exclusion 
    // for all request calling it 
    // on the record with id 1, with "foo" identifier
    sleep(5); 
    echo "done!";  
},null,"foo");


$m->usingDbMutex(function(){ 
    /* 
        in this case we will use also an optimistic lock mechanism
        we can provide the previous value of 
            - counter 
                more reliable but slower, the counter value since is incremented inside a "read lock"
                can't never be the same
                
            and/or

            - model_updated_at (updated_at timestamp of the model)
                can be used if you are making modification on the model
                (model_updated_at would not make sense if your modifications are applied only to someting else)
                less reliable but faster, the updated_at field of the model
                can be read outside of the "read lock" 
                
        if the values do not match the currents, a 412 http error will be returned
        
        NOTE: these values must came from the current REQUEST, not from the retrieved models
    */
},
    [
        'counter' => 10,
        'model_updated_at' => '2020-12-28 14:56:44',
    ] 
);  
// in the case, you want to use the counter value, obviously you need to load the previous value
// when reading the data. You could you use withDbMutex scope as explained below.


// there is also the  withDbMutex scope
YourModel::withDbMutex()->find(1); //will add the "default" dbmutex data
YourModel::withDbMutex('foo')->find(1); //will add the "foo" dbmutex data

警告

在读取包含“dbmutex”关系信息的模型时,您可能需要等待该行的锁变为可用。

建议仅在必要时加载它,例如,如果您需要使用带有计数器值的乐观锁机制。

出于相同的原因,也建议只加载dbmutex相关行的最小数量。

测试

使用以下命令运行测试

vendor/bin/phpunit

贡献

请参阅CONTRIBUTING以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件ivanomatteo@gmail.com联系,而不是使用问题跟踪器。

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件