


这次给大家带来PHP异步进程助手async-helper使用详解,PHP异步进程助手async-helper使用的注意事项有哪些,下面就是实战案例,一起来看一下。
简介
PHP 的异步进程助手,借助于 AMQP 实现异步执行 PHP 的方法,将一些很耗时、追求高可用、需要重试机制的操作放到异步进程中去执行,将你的 HTTP 服务从繁重的业务逻辑中解脱出来。以一个较低的成本将传统 PHP 业务逻辑转换成非阻塞、高可用、可扩展的异步模式。
依赖
php 5.6+
ext-bcmath
ext-amqp 1.9.1+
ext-memcached 3.0.3+
安装
通过 composer 安装
composer require l669/async-helper
或直接下载项目源码
wget https://github.com/l669306630/async-helper/archive/master.zip
使用范例
业务逻辑:这里定义了很多等待被调用的类和方法,在你的项目中这可能是数据模型、或是一个发送邮件的类。
<?php class SendMailHelper { /** * @param array $mail * @throws Exception */ public static function request($mail) { // 在这里发送邮件,或是通过调用第三方提供的服务发送邮件 // 发送失败的时候你抛出了异常,希望被进程捕获,并按设定的规则进行重试 } }
生产者:通常是 HTTP 服务,传统的 PHP 项目或是一个命令行程序,接收到某个请求或指令后进行一系列的操作。
<?php use l669\AsyncHelper; class UserController { public function register() { // 假设这是一个用户注册的请求,用户提交了姓名、邮箱、验证码 // 第一步、校验用户信息 // 第二步、实例化异步助手,这时候会连接 AMQP $async_helper = new AsyncHelper([ 'host' => '127.0.0.1', 'port' => '5672', 'user' => 'root', 'pass' => '123456', 'vhost' => '/' ]); // 第三步、保存用户信息到数据库 $mail = [ 'from' => 'service@yourdomain.com', 'to' => 'username@163.com', 'subject' => '恭喜你注册成功', 'body' => '请点击邮件中的链接完成验证....' ]; // 第四步、通过异步助手发送邮件 $async_helper->run('\\SendMailHelper', 'request', [$mail]); // 这是同步的模式去发送邮件,如果邮件服务响应迟缓或异常,就会直接影响该请求的响应时间,甚至丢失这封重要邮件 // SendMailHelper::request($mail); } }
消费者:PHP 的异步进程,监听消息队列,执行你指定的方法。并且该消费者进程是可扩展的高可用的服务,这一切都得益于 AMQP,这是系统解耦、布局微服务的最佳方案。
consume.php
<?php require_once('vendor/autoload.php'); require_once('SendMailHelper.php'); use l669\AsyncHelper; use l669\CacheHelper; $cache_helper = new CacheHelper('127.0.0.1', 11211); while(true){ try{ $async_helper = new AsyncHelper([ 'host' => '127.0.0.1', 'port' => '5672', 'user' => 'root', 'pass' => '123456', 'vhost' => '/', 'cacheHelper' => $cache_helper ]); $async_helper->consume(); }catch(Exception $e){ // 可以在这里记录一些日志 sleep(2); } }
# 在命令行下启动消费者进程,推荐使用 supervisor 来管理进程
php consume.php
支持事务:需要一次提交执行多个异步方法,事务可以确保完成性。
// 接着上面的示例来说,这里省略了一些重复的代码,下同 $async_helper->beginTransaction(); try{ $async_helper->run('\\SendMailHelper', 'request', [$mail1]); $async_helper->run('\\SendMailHelper', 'request', [$mail2]); $async_helper->run('\\SendMailHelper', 'request', [$mail3]); $async_helper->commit(); }catch(\Exception $e){ $async_helper->rollback(); }
阻塞式重试:当异步进程执行一个方法,方法内部抛出异常时进行重试,一些必须遵循执行顺序的业务就要采用阻塞式的重试,通过指定重试最大阻塞时长来控制。
use l669\CacheHelper; use l669\AsyncHelper; $async_helper = new AsyncHelper([ 'host' => '127.0.0.1', 'port' => '5672', 'user' => 'root', 'pass' => '123456', 'vhost' => '/', 'cacheHelper' => new CacheHelper('127.0.0.1', 11211), 'retryMode' => AsyncHelper::RETRY_MODE_REJECT, // 阻塞式重试 'maxDuration' => 600 // 最长重试 10 分钟 ]); $send_mail_helper = new \SendMailHelper(); $mail = new \stdClass(); $mail->from = 'service@yourdomain.com'; $mail->to = 'username@163.com'; $mail->subject = '恭喜你注册成功'; $mail->body = '请点击邮件中的链接完成验证....'; $async_helper->run($send_mail_helper, 'request', [$mail]); // 如果方法中需要抛出异常来结束程序,又不希望被异步进程重试,可以抛出以下几种错误码,进程捕获到这些异常后会放弃重试: // l669\AsyncException::PARAMS_ERROR // l669\AsyncException::METHOD_DOES_NOT_EXIST // l669\AsyncException::KNOWN_ERROR
非阻塞式重试:当异步执行的方法内部抛出异常,async-helper 会将该方法重新放进队列的尾部,先执行新进入队列的方法,回头再重试刚才执行失败的方法,通过指定最大重试次数来控制。
use l669\CacheHelper; use l669\AsyncHelper; $async_helper = new AsyncHelper([ 'host' => '127.0.0.1', 'port' => '5672', 'user' => 'root', 'pass' => '123456', 'vhost' => 'new', 'cacheHelper' => new CacheHelper('127.0.0.1', 11211), 'queueName' => 'emails.vip', // 给付费的大爷走 VIP 队列 'retryMode' => AsyncHelper::RETRY_MODE_TTL, // 非阻塞式重试 'maxRetries' => 10 // 最多重试 10 次 ]); $mail = new \stdClass(); $mail->from = 'service@yourdomain.com'; $mail->to = 'username@163.com'; $mail->subject = '恭喜你注册成功'; $mail->body = '请点击邮件中的链接完成验证....'; $async_helper->run('\\SendMailHelper', 'request', [$mail]);
应用和解惑
我们采用的是开源的 RabbitMQ 来为我们提供的 AMQP 服务。
你的项目部署在拥有很多服务器节点的集群上,每个节点的程序都需要写日志文件,现在的问题就是要收集所有节点上面的日志到一个地方,方便我们及时发现问题或是做一些统计。所有节点都可以使用 async-helper 异步调用一个写日志的方法,而执行这个写日志的方法的进程只需要在一台机器上启动就可以了,这样所有节点的日志就都实时掌握在手里了。
做过微信公众号开发的都知道,腾讯微信可以将用户的消息推送到我们的服务器,如果我们在 5s 内未及时响应,腾讯微信会重试 3 次,其实这就是消息队列的应用,使用 async-helper 可以轻松的做和这一样的事情。
得益于 RabbitMQ,你可以轻松的横向扩展你的消费者进程的能力,因为 RabbitMQ 天生就支持集群部署,你可以轻松的启动多个消费者进程,或是将消费者进程分布到多台机器上。
如果 RabbitMQ 服务不可用怎么办呢?部署 RabbitMQ 高可用服务是容易的,对外提供单一 IP,这个 IP 是个负载均衡,背后是 RabbitMQ 集群,负载均衡承担对后端集群节点的健康检查。
async-helper 能否承受高并发请求?async-helper 生产者使用的是短连接,也就说在你的 HTTP 还没有响应浏览器的时候 async-helper 就已经结束了工作,你连接 RabbitMQ 的时间是百分之百小于 HTTP 请求的时间的,换言之,只要 RabbitMQ 承受并发的能力超过你的 HTTP 服务的承受并发的能力,RabbitMQ 就永远不会崩,通过横向扩展 RabbitMQ 很容易做到的。
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to implement PHP to delete folders and files under a fixed path
PHP uses asterisks to replace users Partial characters of phone number and email address
The above is the detailed content of Detailed explanation of the use of PHP asynchronous process assistant async-helper. For more information, please follow other related articles on the PHP Chinese website!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.