在工作中要用到消息隊列,但是主管為了追求開發速度,讓用了一個簡易的類 beanstalk
下面來說明這個東西
參考博客:https://my.oschina.net/u/698121/blog/157092
客戶端github地址:https://github.com/davidpersson/beanstalk
由於是在windows環境下實用,在安裝服務端的時候,還需要安裝cygwin,鏈接:https://github.com/caidongyun/beanstalkd-win
一切准備就緒之后。在cmd開啟beanstalkd.exe 我的目錄是D:\beanstalkd\beanstalkd-win-master
現在說一下流程,就是前台輸入數據,但是和不經過客戶端,對這些信息進行單獨的處理
前台 index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>測試專用</title>
</head>
<body>
<form action="duang.php" method="post">
<label for="id">i d :</label><input type="text" name="id"><br/><br/>
<label for="name">name:</label><input type="text" name="name"><br/><br/>
<label for="work">work:</label><input type="text" name="work"><br/><br/>
<input type="submit" value="提交" style="width: 200px">
</form>
</body>
</html>
信息傳送給duang.php進行處理
<?php
if ($_POST){
require 'index.php';
$data = $_POST;
$process = new Tube();
$process->input($data);
}
接收到數據以后,實例化客戶端信息,將數據放入隊列
index.php內容如下
<?php
class Tube
{
public function input($data)
{
require 'src/Client.php';
$beanstalk = new Client();
$beanstalk->connect();
$beanstalk->useTube('zhou');
$string = json_encode($data);
$beanstalk->put(
23,
0,
60,
$string
);
$beanstalk->disconnect();
}
}
其中作為服務端的信息test.php和處理程序 doJob內容如下
<?php
require_once 'src/Client.php';
require_once 'doJob.php';
set_time_limit(0); //無限制執行
$sleep_time = 1; //設置休眠時間,防止CPU跑滿
$beanstalk = new Client();
$beanstalk->connect();
//var_dump($beanstalk->connect());
$beanstalk->watch('zhou');
//var_dump($beanstalk->listTubesWatched());
//var_dump($beanstalk->listTubes());
//var_dump($beanstalk->stats());
//var_dump($beanstalk->statsTube('zhou'));
while (true) {
//設定休眠時間
sleep($sleep_time);
//接收任務
$job = $beanstalk->reserve();
//處理任務
$result = $beanstalk->touch($job['id']);
if ($result) {
doJob($job['body']);
//刪除任務
$beanstalk->delete($job['id']);
} else {
//休眠任務
$beanstalk->bury($job['id'],2);
}
}
客戶端實用doJob對數據進行處理
<?php
//doJob用於處理隊列中的數據 隊列的數據形式為json
function doJob($job){
if (file_exists('test.json')) {
file_put_contents('test.json',$job,8);
}
}