基于redis的setnx实现
在高并发下可以减少直接请求数据库。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| function getRedis() { $redis = new Redis(); $redis->connect('127.0.0.1', 6379, 60); return $redis; }
function lock($key, $random) { $redis = getRedis(); $ret = $redis->set($key, $random, ['nx', 'ex' => 3 * 60]); return $ret; }
function unLock($key, $random) { $redis = getRedis(); if ($redis->get($key) == $random) { $redis->del($key); } }
function getArticleInCache($id) { $redis = getRedis(); $key = 'article_content_' . $id; $ret = $redis->get($key); if ($ret === false) { $lockKey = $key . '_lock'; $random = mt_rand(); if (lock($lockKey, $random)) { $value = $db->getArticle($id); $redis->set($key, $value, 2 * 60); unLock($lockKey, $random); } else { usleep(200); getArticleInCache($id); } } else { return $ret; } }
|