基于redis字符串string类型的简单缓存实现
<?php
$redis = new \Redis();
$redis->connect('127.0.0.1',6379);
$redis->set('cache_key',json_encode(['data'=>'这是缓存数据']));
$data = $redis->get('cache_key');
print_r(json_decode($data,true));
基于redis列表list类型的简单队列实现
<?php
$redis = new \Redis();
$redis->connect('localhost',6379);
$redis->rpush('queue_name',json_encode(['user_id'=>5]));
$redis->rpush('queue_name',json_encode(['user_id'=>6]));
$redis->rpush('queue_name',json_encode(['user_id'=>7]));
echo "数据进队列完成\n";
$res = $redis->lrange('queue_name',0,1000);
print_r($res);
$redis->lpop('queue_name');
$res = $redis->lrange('queue_name',0,1000);
print_r($res);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
基于redis事务的乐观锁实现
<?php
$redis = new \Redis();
$redis->connect('localhost',6379);
$redis->watch('count');
$redis->multi();
$redis->set('count',time());
sleep(10);
$res = $redis->exec();
if($res){
echo 'sucesss';
return;
}else{
echo 'fail';
}
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
基于redis的发布订阅实现
发布publish.php
<?php
$redis = new \Redis();
$redis->connect('localhost',6379);
$redis->publish('msg','来自xxx频道的消息推送');
echo '消息推送成功';
$redis->close();
订阅subscribe.php
<?php
$redis = new \Redis();
$redis->pconnect('localhost',6379);
echo "订阅频道等待消息推送\n";
$redis->subscribe(['msg'],'callfun');
function callfun($redis,$channel,$msg){
print_r(['redis'=>$redis,'channel'=>$channel,'msg'=>$msg]);
}
来自 https://blog.csdn.net/github_26672553/article/details/57073562