redis常见使用场景下PHP实现
生活随笔
收集整理的這篇文章主要介紹了
redis常见使用场景下PHP实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于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));- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
基于redis列表list類型的簡單隊列實現
<?php//利用列表list實現簡單隊列 $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);//監視count的值 $redis->watch('count');//開啟事務 $redis->multi();//操作count $redis->set('count',time());//-------------------------------- //模擬并發下其他進程對count的操作 //redis-cli 執行 $redis->set('count','is simulate'); 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();- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
訂閱subscribe.php
<?php //訂閱//ini_set('default_socket_timeout',-1);$redis = new \Redis(); $redis->pconnect('localhost',6379);//訂閱 echo "訂閱頻道等待消息推送\n";$redis->subscribe(['msg'],'callfun'); //msg 是頻道名//回調 function callfun($redis,$channel,$msg){print_r(['redis'=>$redis,'channel'=>$channel,'msg'=>$msg]); }來源:https://blog.csdn.net/github_26672553/article/details/57073562
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的redis常见使用场景下PHP实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 澄空学园动漫(澄空学园)
- 下一篇: PHP 如何在Redis中实现事物(事物