指定keyspace
$ redis-cli -n 1 KEYS '*'
獲取key值
127.0.0.1:6379[1]> GET "laravel_cache:App\\Models\\User:15"
xxx
亦可下載redis gui管理工具: redis desktop manager
使用Redis鎖處理併發問題
redis命令> SET lockKey value NX EX 30
NX -- 當key不存在時才能設置
NX -- Only set the key if it does not already exist. - "SET if Not eXists"
EX seconds -- 設置過期時間(秒)
EX seconds -- Set the specified expire time, in seconds.
邏輯
try {if (! $lock = RedisLock::lock('do-some-thing', 100000)) {
throw new Exception('Resource locked.');
}
// 業務邏輯
} catch (Exception $e) {
throw $e;
} finally {
RedisLock::unlock($lock);
}
實現
$time = microtime();$max = 1000; //1 second
do { //针对问题1,使用循环
$timeout = 10;
$roomid = 10001;
$key = 'room_lock';
$value = 'room_'.$roomid; //分配一个随机的值针对问题3
$isLock = Redis::set($key, $value, 'ex', $timeout, 'nx');//ex 秒
if ($isLock) {
if (Redis::get($key) == $value) { //防止提前过期,误删其它请求创建的锁
//执行内部代码
Redis::del($key);
continue;//执行成功删除key并跳出循环
}
} else {
usleep(5000); //睡眠,降低抢锁频率,缓解redis压力,针对问题2
}
} while(!$isLock && ((microtime() - $time) < $max) );
綠色:限制時間,避免等太久
__destruct() 可能要解鎖,避免「內部代碼」異常一直鎖著
laradock中容器連host的redis報錯
https://blog.51cto.com/crfsz/1878137 redis解决(DENIED Redis is running in protected mode because prote)
DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
原因
redis 的protected mode被開啟
解法
編輯 /etc/redis.conf
重啟redis
# service redis restart
檢查
# redis-cli
127.0.0.1:6379> CONFIG GET protected*
1) "protected-mode"
2) "no"
參考資料:
https://blog.csdn.net/iastro/article/details/83304188 redis锁处理并发问题https://www.jianshu.com/p/81b0f1bd1328 Redis锁机制的几种实现方式
https://github.com/ginnerpeace/laravel-redis-lock/blob/master/src/Processor.php laravel-redis-lock
沒有留言:
張貼留言