Commonly used locking methods are:
(Learning video sharing: redis video tutorial)
1. Add incr Lock
<?php $redis = new Redis(); $redis->connect('127.0.0.1'); $redis->multi(); $redis->incr('number'); //$redis->decr('number'); //$redis->expire('number', -1); var_dump($redis->get('number')); var_dump($redis->ttl('number'));
2. Setnx lock
<?php $redis->setnx('name', 'felix'); var_dump($redis->get('name')); var_dump($redis->ttl('name'));
3. Set lock
<?php $redis->set('like', 'chuangxi', ['nx', 'ex' => 10]); //$redis->del('like'); var_dump($redis->get('like')); var_dump($redis->ttl('like'));
4. Prevent deadlock
<?php $isLock = false; do { $isLock = $redis->set('like', 'a', ['nx', 'ex' => 10]); if($isLock) { if($redis->get('like') == 'a') { //执行逻辑 $redis->del('like'); continue; } } else { usleep(5000); } } while (!$isLock); //redis事务 $redis->set(); $redis->watch(['number', 'like']);
Related recommendations: redis tutorial
The above is the detailed content of What are the common ways to lock redis?. For more information, please follow other related articles on the PHP Chinese website!