redis实战
optimistic-lock.php
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
<?php
/**
* redis实战
* Redis practice
*
* 实现乐观锁机制
* To achieve optimistic lock
*
* @author <https://github.com/wuxiumu>
*/
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
// 监视 count 值
// monitor count value
$redis->watch('count');
// 开启事务
// begin transaction
$redis->multi();
// 操作count
// operating count
$time = time();
$redis->set('count', $time);
//-------------------------------
/**
* 模拟并发下其他进程进行set count操作 请执行下面操作
* simulation another user operating `set count`, please execute
*
* redis-cli 执行 $redis->set('count', 'is simulate'); 模拟其他终端
* use redis-cli execute `set count 'is simulate'`
*/
sleep(10);
//-------------------------------
// 提交事务
// commit transcation
$res = $redis->exec();
if ($res) {
// 成功...
echo 'success:' . $time . "\n";
return;
}
// 失败...
echo 'fail:' . $time . "\n";