Redis 事務踩坑
Redis 測試 Demo
<?php # 原子操作 redis 事務 $redis = new \Redis(); $redis->connect('127.0.0.1', '6379', 3); // 監控key WATCH事務開啟前監控key $redis->WATCH('test_hash'); // 開啟事務 $redis->MULTI(); // 事務內執行寫操作 $redis->set('test_hash', 2); $redis->set('test_hash', 1); // 提交事務 $redis->exec(); // 回滾事務 // $redis->discard();
redis 事務 需要通過 redis-climonitor 監控中看到 正常提交流程
`
1544372307.803143 [0 127.0.0.1:37532] "MULTI" 1544372307.803225 [0 127.0.0.1:37532] "WATCH" "test_hash" 1544372308.923998 [0 127.0.0.1:37502] "SET" "test_hash" "2" 1544372312.803550 [0 127.0.0.1:37532] "SET" "test_hash" "1" 1544372312.803566 [0 127.0.0.1:37532] "EXEC" 1544372318.742735 [0 127.0.0.1:37502] "get" "test_hash"
如果事務中 中間監控key 發生變動 就會變成
1544372363.760832 [0 127.0.0.1:37556] "WATCH" "test_hash" 1544372363.760935 [0 127.0.0.1:37556] "MULTI" 1544372366.129051 [0 127.0.0.1:37502] "set" "test_hash" "2" 1544372368.761290 [0 127.0.0.1:37556] "EXEC"
從monitor 日誌 可以看到37556
埠例項監控test_hash
,37502
埠例項修改了test_hash
exec 仍然提交 但中間沒有提交
"SET" "test_hash" "2" "SET" "test_hash" "1"
開發中 PHP demo 操作exec
返回
成功 :
array(2) { [0] => bool(true) [1] => bool(true) }
失敗 :
bool(false)
還有個小彩蛋 測試了下 將test_hash
型別改外其他 hash 或 zset 事務提交也會成功, 成功後將test_hash 改成 string 型別了. 這又點霸道了.
測試環境 redis 3.2.12
最後更新於2018-12-0916:49:47 並被新增「redis」標籤,已有 1 位童鞋閱讀過。