malkusch/lock
Composer 安装命令:
composer require malkusch/lock
包简介
Mutex library for exclusive code execution.
关键字:
README 文档
README
Requirements | Installation | Usage | Implementations | Authors | License
php-lock/lock
This library helps executing critical code in concurrent situations in serialized fashion.
php-lock/lock follows semantic versioning.
Requirements
- PHP 7.4 - 8.5
- Optionally nrk/predis to use the Predis locks.
- Optionally the php-pcntl extension to enable locking with
flock()without busy waiting in CLI scripts. - Optionally
flock(),ext-redis,ext-pdo_mysql,ext-pdo_sqlite,ext-pdo_pgsqlorext-memcachedcan be used as a backend for locks. See examples below. - If
ext-redisis used for locking and is configured to use igbinary for serialization or lzf for compression, additionallyext-igbinaryand/orext-lzfhave to be installed.
Installation
Composer
To use this library through composer, run the following terminal command inside your repository's root folder.
composer require malkusch/lock
Usage
This library uses the namespace Malkusch\Lock.
Mutex
The Malkusch\Lock\Mutex\Mutex interface provides the base API for this library.
Mutex::synchronized()
Malkusch\Lock\Mutex\Mutex::synchronized() executes code exclusively. This
method guarantees that the code is only executed by one process at once. Other
processes have to wait until the mutex is available. The critical code may throw
an exception, which would release the lock as well.
This method returns whatever is returned to the given callable. The return
value is not checked, thus it is up to the user to decide if for example the
return value false or null should be seen as a failed action.
Example:
$newBalance = $mutex->synchronized(static function () use ($bankAccount, $amount) { $balance = $bankAccount->getBalance(); $balance -= $amount; if ($balance < 0) { throw new \DomainException('You have no credit'); } $bankAccount->setBalance($balance); return $balance; });
Mutex::check()
Malkusch\Lock\Mutex\Mutex::check() sets a callable, which will be
executed when Malkusch\Lock\Util\DoubleCheckedLocking::then() is called,
and performs a double-checked locking pattern, where it's return value decides
if the lock needs to be acquired and the synchronized code to be executed.
See https://en.wikipedia.org/wiki/Double-checked_locking for a more detailed explanation of that feature.
If the check's callable returns false, no lock will be acquired and the
synchronized code will not be executed. In this case the
Malkusch\Lock\Util\DoubleCheckedLocking::then() method, will also return
false to indicate that the check did not pass either before or after acquiring
the lock.
In the case where the check's callable returns a value other than false, the
Malkusch\Lock\Util\DoubleCheckedLocking::then() method, will
try to acquire the lock and on success will perform the check again. Only when
the check returns something other than false a second time, the synchronized
code callable, which has been passed to then() will be executed. In this case
the return value of then() will be what ever the given callable returns and
thus up to the user to return false or null to indicate a failed action as
this return value will not be checked by the library.
Example:
$newBalance = $mutex->check(static function () use ($bankAccount, $amount): bool { return $bankAccount->getBalance() >= $amount; })->then(static function () use ($bankAccount, $amount) { $balance = $bankAccount->getBalance(); $balance -= $amount; $bankAccount->setBalance($balance); return $balance; });
LockReleaseException::getCode{Exception, Result}()
Mutex implementations based on Malkush\Lock\Mutex\AbstractLockMutex will throw
Malkusch\Lock\Exception\LockReleaseException in case of lock release
problem, but the synchronized code block will be already executed at this point.
In order to read the code result (or an exception thrown there),
LockReleaseException provides methods to extract it.
Example:
try { $result = $mutex->synchronized(static function () { if (someCondition()) { throw new \DomainException(); } return 'result'; }); } catch (LockReleaseException $e) { if ($e->getCodeException() !== null) { // do something with the $e->getCodeException() exception } else { // do something with the $e->getCodeResult() result } throw $e; }
Implementations
You can choose from one of the provided Malkusch\Lock\Mutex\Mutex interface
implementations or create/extend your own implementation.
FlockMutex
The FlockMutex is a lock implementation based on
flock().
Example:
$mutex = new FlockMutex(fopen(__FILE__, 'r'));
Timeouts are supported as an optional second argument. This uses the ext-pcntl
extension if possible or busy waiting if not.
MemcachedMutex
The MemcachedMutex is a spinlock implementation which uses the
Memcached extension.
Example:
$memcached = new \Memcached(); $memcached->addServer('localhost', 11211); $mutex = new MemcachedMutex('balance', $memcached);
RedisMutex
The RedisMutex is a lock implementation which supports the
phpredis extension
or Predis API clients.
Both Redis and Valkey servers are supported.
If used with a cluster of Redis servers, acquiring and releasing locks will continue to function as long as a majority of the servers still works.
Example:
$redis = new \Redis(); $redis->connect('localhost'); // OR $redis = new \Predis\Client('redis://localhost'); $mutex = new RedisMutex($redis, 'balance');
SemaphoreMutex
The SemaphoreMutex is a lock implementation based on Semaphore.
Example:
$semaphore = sem_get(ftok(__FILE__, 'a')); $mutex = new SemaphoreMutex($semaphore);
MySQLMutex
The MySQLMutex uses MySQL's
GET_LOCK
function.
Both MySQL and MariaDB servers are supported.
It supports timeouts. If the connection to the database server is lost or interrupted, the lock is automatically released.
Note that before MySQL 5.7.5 you cannot use nested locks, any new lock will silently release already held locks. You should probably refrain from using this mutex on MySQL versions < 5.7.5.
Also note that GET_LOCK function is server wide and the MySQL manual suggests
you to namespace your locks like dbname.lockname.
$pdo = new \PDO('mysql:host=localhost;dbname=test', 'username'); $mutex = new MySQLMutex($pdo, 'balance', 15);
PostgreSQLMutex
The PostgreSQLMutex uses PostgreSQL's advisory locking functions.
Named locks are offered. PostgreSQL locking functions require integers but the conversion is handled automatically.
It supports timeouts. If the connection to the database server is lost or interrupted, the lock is automatically released.
$pdo = new \PDO('pgsql:host=localhost;dbname=test', 'username'); $mutex = new PostgreSQLMutex($pdo, 'balance');
DistributedMutex
The DistributedMutex is the distributed lock implementation of
RedLock which supports
one or more Malkush\Lock\Mutex\AbstractSpinlockMutex instances.
Example:
$mutex = new DistributedMutex([ new \Predis\Client('redis://10.0.0.1'), new \Predis\Client('redis://10.0.0.2'), ], 'balance');
Authors
Since year 2015 the development was led by Markus Malkusch, Willem Stuursma-Ruwen and many GitHub contributors.
Currently this library is maintained by Michael Voříšek - GitHub | LinkedIn.
Commercial support is available.
License
This project is free and is licensed under the MIT.
malkusch/lock 适用场景与选型建议
malkusch/lock 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.06M 次下载、GitHub Stars 达 945, 最近一次更新时间为 2015 年 07 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「redis」 「mysql」 「postgresql」 「memcached」 「locking」 「lock」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 malkusch/lock 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 malkusch/lock 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 malkusch/lock 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
SilverStripe now has tentative support for PostgreSQL ('Postgres')
Dibi is Database Abstraction Library for PHP
Microservice RPC through message queues.
The CodeIgniter Redis package
贝嘟分布式缓存扩展
Sql dumps containing databases for the linna apps.
统计信息
- 总下载量: 10.06M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 963
- 点击次数: 31
- 依赖项目数: 27
- 推荐数: 2
其他信息
- 授权协议: MIT
- 更新时间: 2015-07-12