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-cli monitor 监控中看到 正常提交流程
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 事务开启后 同实例下读操作是不可用的 返回 queue 规避方式就是用其他实例取做读操作, 反正已经watch 了 不用担心读到脏数据;
测试环境 redis 3.2.12
最后 要补充的是 Redis 集群版本不支持事务操作