Beanstalk消息队列的实现

 在工作中要用到消息队列,但是主管为了追求开发速度,让用了一个简易的类  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:eanstalkdeanstalkd-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=" 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);
}
}

原文地址:https://www.cnblogs.com/zhouqi666/p/5977976.html