内容简介:Redis 分布式锁解决方案
在论坛上找到各种版本,应用到项目出运行不了,各种报错。今天自己重新编写调试测试,运行成功。
- PHP redis使用phpredis
- 参考redis官方资料
-
具体代码
<?php namespace app\common\service; /** * * redis 加锁 --单 Redis 实例实现分布式锁 * * -- 分布式请使用:Redlock:https://github.com/ronnylt/redlock-php * -- 详情参考: http://www.redis.cn/topics/distlock.html * * @package app\common\service */ class RedisLock { const LOCK_SUCCESS = 'OK'; const IF_NOT_EXISTS = 'NX'; const MILLISECOND_EXPIRE_TIME = 'PX'; const EXPIRE_TIME = 60000; // millisecond => 60s const LOCK_VALUE = 1; /** * 加锁 * @param $redis object * @param $key * @param string $expire_time 60000 */ public static function lock($redis, $key, $expire_time='') { if (empty($expire_time)) { $expire_time = self::EXPIRE_TIME; } $result = $redis->set($key, self::LOCK_VALUE, [self::IF_NOT_EXISTS, self::MILLISECOND_EXPIRE_TIME => $expire_time]); return self::LOCK_SUCCESS === (string)$result; } /** * 解锁 * * 参考: https://github.com/phpredis/phpredis/blob/develop/tests/RedisTest.php * @param $redis * @param $key */ public static function unlock($redis, $key) { $lua =<<<EOT if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end EOT; $result = $redis->eval($lua, array($key, self::LOCK_VALUE), 1); return $result; } }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Cascading Style Sheets 2.0 Programmer's Reference
Eric A. Meyer / McGraw-Hill Osborne Media / 2001-03-20 / USD 19.99
The most authoritative quick reference available for CSS programmers. This handy resource gives you programming essentials at your fingertips, including all the new tags and features in CSS 2.0. You'l......一起来看看 《Cascading Style Sheets 2.0 Programmer's Reference》 这本书的介绍吧!