新浪云-使用 PHP-Resque 实现后台任务

来源:互联网 发布:淘宝互刷代付骗局 编辑:程序博客网 时间:2024/06/05 18:06

概述

php-resque 是一个基于 Redis 的队列库,是 resque 项目的 PHP Fork 版本。

安装

使用 php-resque 之前,需要先安装,可以使用 composer 进行。

$ composer require sinacloud/php-resque:dev-masterLoading composer repositories with package informationUpdating dependencies (including require-dev)  - Installing colinmollenhour/credis (1.7)    Loading from cache  - Installing psr/log (1.0.0)    Loading from cache  - Installing chrisboulton/php-resque (dev-master 73b62e3)    Cloning 73b62e364a89230d041abd2ba767bcec6fa15927Writing lock fileGenerating autoload files

将 vendor 目录和应用代码一起提交入代码仓库,即可在服务端的代码里使用 php-resque 了。

添加任务描述类

创建一个 job.php 文件,这个文件里定义需要运行的任务。

<?phpclass My_Job{    public function perform()    {        // Work work work        echo $this->args['name'];    }}

创建后台工作进程

创建一个 worker.php 文件,这个模块会监听 Redis 队列并处理任务。

<?phpdate_default_timezone_set('Asia/Shanghai');$redis = "redis 连接地址";require 'job.php';putenv("QUEUE=default");putenv("REDIS_BACKEND=$redis");require 'vendor/bin/resque';

在应用代码根目录下创建一个 Procfile 文件,如下添加一个新的后台进程。

worker: php worker.php

添加任务

在 Web 应用程序的处理函数中,使用如下代码添加任务。

<?phprequire 'vendor/autoload.php';$redis = "redis 连接地址";Resque::setBackend($redis);$args = array(    'name' => 'Chris');Resque::enqueue('default', 'My_Job', $args);

执行完 enqueue 后,任务就会被添加到 Redis 队列中去异步执行,后台进程会不停的从 Redis 队列中取出任务并执行。

部署

将上面的代码提交入代码仓库并 push 到服务端,ta-dah! 完成。你可以在『应用/后台进程』页面来重启或者调整进程数目。如果进程启动有问题,你可以在 HTTP 错误日志里看到后台进程的详细错误日志来解决问题。







原文地址:http://www.sinacloud.com/doc/sae/php/background-jobs-with-resque.html

0 0
原创粉丝点击