?php/** * 使用Memcache实现给进程加锁的类 * * Copyright (C) 2013 JeffJing * * 一些时候需要让系统的某些操作串行化,这个时候就要对这些操作来加上一把锁。 好比你去上厕所, 你要先推厕所门看能否进去,进去的话上锁,其他人就进不来了, 等你拉完粑粑之
<?php /** * 使用Memcache实现给进程加锁的类 * * Copyright (C) 2013 JeffJing * * 一些时候需要让系统的某些操作串行化,这个时候就要对这些操作来加上一把锁。 好比你去上厕所, 你要先推厕所门看能否进去,进去的话上锁,其他人就进不来了, 等你拉完粑粑之后把锁打开,这样的话就保证了厕所永远只有1个人, 上厕所的过程是串行化的, 同时只有1个人上。 * 网上的一些解决方案大多是使用文件的, 我就纳闷了,加锁的时候创建一个文件, 解锁的时候把文件删掉。 * 我就纳闷: Why not memcached ? 顺手写了这么一个 , 希望对大家"拉粑粑"的这种操作有所帮助 * * 举个栗子: * $key = '厕锁'; * if(MemLock::addLoack($key)) { * //拉粑粑喽,pu~pu~~~~~ * MemLock::releaseLock($key); * } else { * //不好意思, 厕所有人啦!! * } * */ class MemLock { private static $memcache = null; /** * 获取memcached连接 * * @return Memcached */ public static function getConnection() { if (! isset ( self::$memcache )) { self::$memcache = new Memcache (); self::$memcache->connect ( '127.0.0.1', 11211 ); } return self::$memcache; } /** * 加锁 * * @param $key 锁关键字 * @param $expireTime 超时时间, 当进程在锁定后出错,这样永远不会释放锁了,只能等到缓存失效 * * @return boolean true 成功获取到锁 false 获取锁失败 */ public static function addLock($key, $expireTime = 120) { $memcache = self::getConnection (); if($memcache->add($key, 1, false, $expireTime)) { return true; } return false; } /** * 释放锁 * * @param $key 锁关键字 * * @return boolean true 释放成功 false 释放失败 */ public static function releaseLock($key) { $memcache = self::getConnection (); return $memcache->delete ( $key ); }
声明: 本文采用 CC BY-NC-SA 3.0 协议进行授权
转载请注明来源:小景的博客
本文链接地址:http://www.phpv5.com/blog/mem-lock

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor