php+redis實現訊息佇列

語言: CN / TW / HK

php+redis訊息佇列是php+mysql效能不足時的一箇中間處理方案.

通過這個中間的處理,保證的資料的可用性和準確性。用於伺服器瞬間請求大,資料庫壓力大的情況。如併發量大導致的超賣、併發量大導致的資料重複情況。

流程:php接受請求和資料 -> php把資料寫入redis佇列中(入隊) -> shell定時呼叫php讀取佇列資料寫入mysql(出隊)

實現程式碼:

入隊:inqueue.php

<?php
$redis = new redis();
$redis->connect('127.0.0.1',6379);
$redis -> select('1');
$redis->auth('');
  
$data = [a,b,c,d,e,f,g,h]; //這裡可以是get或post請求過來的資料
$data = json_encode($data);
$in = $redis->rpush('queue',$data);
if($in){
    echo "入隊成功";
}

出隊:outqueue.php

#!/usr/bin/php
<?php
$redis = new redis();
$redis->connect('127.0.0.1',6379);
$redis -> select('1');
$redis->auth('');
  
$value = $redis->lpop('queue');
$value = json_decode($value,true);

shell process.sh:定時呼叫outqueue.php指令碼

#進行每分鐘呼叫一次
* * * * * /usr/local/nginx/html/process.sh
#!/bin/bash
#file_name : process.sh
#author : zuoping
php /usr/local/nginx/html/outqueue.php

*如果每分鐘呼叫一次頻率不夠,可以執行多次呼叫指令碼,如:

#!/bin/bash
#file_name : process.sh
#author : zuoping
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
php /usr/local/nginx/html/outqueue.php
#這樣就一分鐘呼叫了多次了。

檢視佇列中的當前資料:

<?php
$redis = new redis();
$redis->connect('127.0.0.1',6379);
$redis -> select('1');
$redis->auth('');
  
$list = $redis->lrange('queue',0,-1);
var_dump($list);

以上內容希望幫助到大家,很多PHPer在進階的時候總會遇到一些問題和瓶頸,業務程式碼寫多了沒有方向感,更多PHP大廠PDF面試文件,PHP進階架構視訊資料,PHP精彩好文免費獲取可以關注公眾號:PHP開源社群,或者訪問:

2021金三銀四大廠面試真題集錦,必看!

四年精華PHP技術文章整理合集——PHP框架篇

四年精華PHP技術文合集——微服務架構篇

四年精華PHP技術文合集——分散式架構篇

四年精華PHP技術文合集——高併發場景篇

四年精華PHP技術文章整理合集——資料庫篇