herroffizier/yiicachemutex

基于 Yii 缓存组件的互斥锁实现

dev-master 2014-03-17 08:59 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:16:30 UTC


README

YiiCacheMutex 是一个基于 Yii 缓存组件的互斥锁实现,适用于 Yii 框架。

使用方法

首先,将此存储库中的文件复制到 extensions/yiicachemutex 目录,并将 YiiCacheMutex 添加到 Yii 应用程序中

return array(
...
    'components'=>array(
        ...
        'cacheMutex' => array(
            'class' => 'ext.yiicachemutex.YiiCacheMutex',
            // Cache component name.
            // Useful when you want to use separate cache for mutexes.
            'cacheName' => 'cache',
            // Time in microseconds to sleep between cache pollings.
            'sleepTime' => 100,
            // Time in seconds for mutex to expire.
            // If set to 0 mutex will never expire but this is not recommended.
            'expireTime' => 300,
        ),
        ...
    ),
...
);

之后,您可以通过调用 Yii::app()->cacheMutex->acqiure() 创建互斥锁,并通过调用 Yii::app()->cacheMutex->release() 释放它们。互斥锁的获取可以是阻塞的或非阻塞的。对于阻塞获取,可以设置超时时间。此外,互斥锁还可以设置过期时间,这被强烈推荐以避免死锁。

使用示例

// Get mutex 'test' if it's free, otherwise wait for it's release forever.
Yii::app()->cacheMutex->acquire('test');

// Get mutex 'test' if it's free, otherwise return false immeditely.
Yii::app()->cacheMutex->acquire('test', 0);

// Wait 0.5s for mutex 'test' to be released.
Yii::app()->cacheMutex->acquire('test', 500000);

// Release acquired by current thread mutex 'test'.
Yii::app()->cacheMutex->release('test');