PHPackages                             motian/lock - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. motian/lock

ActiveLibrary

motian/lock
===========

支持Redis与Memcached的并发锁。

1.6(7y ago)055MITPHPPHP &gt;=5.5.9

Since Mar 8Pushed 7y ago1 watchersCompare

[ Source](https://github.com/motian/Lock)[ Packagist](https://packagist.org/packages/motian/lock)[ RSS](/packages/motian-lock/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (1)Dependencies (1)Versions (5)Used By (0)

Lock
====

[](#lock)

这是一个支持 Laravel 5 的并发锁拓展包。

该模块在 Redis 与 Memcache 上实现了锁机制。

注意：集群环境下，必须使用 Redis 驱动，否则由于 Memcache 的特性，锁可能出现上锁不准确的情况。

安装
--

[](#安装)

```
composer require latrell/lock dev-master

```

使用 `composer update` 更新包列表，或使用 `composer install` 安装。

找到 `config/app.php` 配置文件中的 `providers` 键，注册服务提供者。

（Laravel 5.5 以上版本可跳过该步骤）

```
    'providers' => [
        // ...
        Latrell\Lock\LockServiceProvider::class,
    ]
```

找到 `config/app.php` 配置文件中的 `aliases` 键，注册别名。

```
    'aliases' => [
        // ...
        'Lock' => Latrell\Lock\Facades\Lock::class,
    ]
```

运行 `php artisan vendor:publish` 命令，发布配置文件到你的项目中。

使用
--

[](#使用)

### 闭包方式

[](#闭包方式)

使用闭包的方式，自动解锁，防止死锁；上锁失败时抛出 AcquireFailedException 异常

需注意，外部变量需要使用 `use` 引入才可在闭包中使用。

```
// 防止商品超卖。
$key = 'Goods:' . $goods_id;
Lock::granule($key, function() use($goods_id) {
    $goods = Goods::find($goods_id);
    if ($goods->stock > 0) {
        // ...
    }
});

// synchronized 是 granule的别名
try {
    $key = md5($user_id . ':' . $udid); // 用户ID+设备ID，防止重复下单
    Lock::synchronized($key, function() use($data) {
        $orderService->createOrder($data)
        // ...
    }, 0);
} catch (AcquireFailedException $e) {
    // 请求过于频繁，请稍后再试
}
```

### 普通方式

[](#普通方式)

提供手动上锁与解锁方式，方便应用在复杂环境。

```
// 锁名称。
$key = 'Goods:' . $goods_id;

// **注意：除非特别自信，否则一定要记得捕获异常，保证解锁动作。**
try {
    // 上锁成功（max_timeout 为0时不会等待当前持有锁的任务运行完成）
    if (Lock::acquire($key, 0)) {
        // acquire 为true表示上锁成功，false表示锁被占用或上锁等待超时
        // 第二个参数指定上锁最大超时时间（秒），不指定则默认使用配置文件设置
        // 逻辑单元。
        $goods = Goods::find($goods_id);
        if ( $goods->stock > 0 ) {
            // ...
        }
    }
} finally {
    // 解锁。
    Lock::release($key);
}
```

### 中间件

[](#中间件)

使用中间件的方式，让两个相同指纹的请求同步执行。

找到 `app/Http/Kernel.php` 中的 `$routeMiddleware` 配置，添加中间件配置。

```
    protected $routeMiddleware = [
        // ...
        'synchronized' => \Latrell\Lock\Middleware\SynchronizationRequests::class,
    ];

```

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 68% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~415 days

Total

3

Last Release

2889d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/437435ba16dc990f9d7212f6af3aed7c3d8b8f760b17a77f7a7dbb246cf8d679?d=identicon)[motian](/maintainers/motian)

---

Top Contributors

[![latrell](https://avatars.githubusercontent.com/u/6267962?v=4)](https://github.com/latrell "latrell (17 commits)")[![motian](https://avatars.githubusercontent.com/u/2382215?v=4)](https://github.com/motian "motian (8 commits)")

---

Tags

laravellaravel 5l5lock

### Embed Badge

![Health badge](/badges/motian-lock/health.svg)

```
[![Health](https://phpackages.com/badges/motian-lock/health.svg)](https://phpackages.com/packages/motian-lock)
```

###  Alternatives

[latrell/alipay

支付宝SDK在Laravel5封装包。

40349.2k](/packages/latrell-alipay)[latrell/lock

支持Redis与Memcached的并发锁。

3222.8k](/packages/latrell-lock)[addons/elasticsearch

Laravel's elasticsearch Paginator/Collection/Logger Helper.

472.5k](/packages/addons-elasticsearch)[latrell/rongcloud

融云服务端SDK在Laravel的封装包。

2111.7k](/packages/latrell-rongcloud)[latrell/geohash

This package geohash for Laravel 5 support.

1128.3k](/packages/latrell-geohash)[latrell/qqwry

纯真 IP 库 Laravel 版 。

274.7k](/packages/latrell-qqwry)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
