Home Backend Development PHP7 PHP7 production environment queue Beanstalkd correct usage posture

PHP7 production environment queue Beanstalkd correct usage posture

May 18, 2020 pm 05:47 PM
php

PHP7 production environment queue Beanstalkd correct usage posture

Application scenarios

Why should I use it? What are the benefits? This should be said at the very beginning. Only when you understand what a thing does and what it is suitable for, can you better integrate it with your own projects. Wherever you use it, you will learn it. If you don’t use it after learning it, it means you don’t know it. We usually just You should consider more questions like this: What project functions can you build that can be combined with xx technology? Is this xx technology feasible in this business scenario? Rather than "What can I do if I learn this XX technology? The company doesn't use it now, so it's useless if I learn it." It must be very painful to learn XX technology with such a mood.

Everyone knows that queues do not do some time-consuming operations first, but are buried first, and then processed asynchronously. In this way, users cannot feel some time-consuming operations such as sending emails and text messages. Yes, because the burying point is over, the operation is over, and the consumption queue is all done on the server. It is mainly used in SMS or email notifications, accessing third-party interfaces to subscribe to messages, and some flash sales activities in the mall, all of which can be completed in combination with queues.

Beanstalkd Introduction

Beanstalkd is a high-performance, lightweight distributed memory queue, C code, typical Memcached-like design, protocol and usage. The same style, so users who have used memcached will feel that Beanstalkd is familiar.

The original design intention of beanstalkd is to execute time-consuming requests asynchronously and return results in time to reduce the response delay of requests under highly concurrent network requests.

Ubuntu installation

sudo apt-get install beanstalkd
Copy after login

Configuration file

vim /etc/default/beanstalkd
Copy after login

View status

service beanstalkd status
# 命令回显 #
root@:/www/server/php/72/etc# service beanstalkd status
● beanstalkd.service - Simple, fast work queue
   Loaded: loaded (/lib/systemd/system/beanstalkd.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2018-10-16 10:42:28 CST; 6 days ago
     Docs: man:beanstalkd(1)
 Main PID: 7033 (beanstalkd)
    Tasks: 1 (limit: 4634)
   CGroup: /system.slice/beanstalkd.service
           └─7033 /usr/bin/beanstalkd -l 0.0.0.0 -p 11300 -b /var/lib/beanstalkd
Oct 16 10:42:28 ip-10-93-2-137 systemd[1]: Started Simple, fast work queue.
Copy after login

Configure connectivity persistence

ip Use 0.0.0.0 to allow all connections, configure security groups or firewalls to restrict connections, release the -b parameter (no persistence by default), memory The queue messages can be logged to the hard disk binlog for persistence, and the queue messages can be re-read when the power is turned off.

vim /etc/default/beanstalkd
BEANSTALKD_LISTEN_ADDR=0.0.0.0
BEANSTALKD_LISTEN_PORT=11300
BEANSTALKD_EXTRA="-b /var/lib/beanstalkd"
Copy after login

beanstalkd Task Status

StatusComments
delayedDelayed status
readyReady status
reservedThe consumer reads out the task and processes it
#buriedReserved status
deleteDelete status

管理工具

亲测了很多网上能找到的 beanstalkd 工具,这两款是我最中意的了,一个命令行,一个 web 的。

命令行:https://github.com/src-d/beanstool

web 界面:https://github.com/ptrofimov/beanstalk_console

编程语言客户端

PHP 客户端

https://packagist.org/packages/pda/pheanstalk

composer require pda/pheanstalk
Copy after login

写入 job

<?php
//创建队列消息
require_once(&#39;./vendor/autoload.php&#39;);
use Pheanstalk\Pheanstalk;
$pheanstalk = new Pheanstalk(&#39;127.0.0.1&#39;,11300);
$tubeName = &#39;email_list&#39;;
$jobData = [
    &#39;email&#39; => &#39;123456@163.com&#39;,
    &#39;message&#39; => &#39;Hello World !!&#39;,
    &#39;dtime&#39; => date(&#39;Y-m-d H:i:s&#39;),
];
$pheanstalk->useTube( $tubeName)->put( json_encode( $jobData ) );
Copy after login

消费 job

<?php
ini_set(&#39;default_socket_timeout&#39;, 86400*7);
ini_set( &#39;memory_limit&#39;, &#39;256M&#39; );
// 消费队列消息
require_once(&#39;./vendor/autoload.php&#39;);
use Pheanstalk\Pheanstalk;
$pheanstalk = new Pheanstalk(&#39;127.0.0.1&#39;,11300);
$tubeName = &#39;email_list&#39;;
while ( true )
{
    // 获取队列信息, reserve 阻塞获取
    $job = $pheanstalk->watch( $tubeName )->ignore( &#39;default&#39; )->reserve();
    if ( $job !== false )
    {
        $data = $job->getData();
        /* TODO 逻辑操作 */
        /* 处理完成,删除 job */
        $pheanstalk->delete( $job );
    }
}
Copy after login

default_socket_timeout 这个参数是一定要加的,php 默认一般是 60s,假如您没有在代码里面设置,采用默认的话(60s),60s 之内如果没有 job 产生,脚本就会报 socket 错误,我写的是 7 天超时,您可以根据业务去调整,记住一定要配置,网上很多搜的 consumer 脚本都没有配置这个,根本不能投入生产环境使用,这是我亲自实践的结果。

  关于 while true 是否死循环,很明确告诉你是死循环,但是不会一直耗性能的那样执行下去,它会在 reserve 这里阻塞不动,直到有消息产生才会往下走,所以大可放心使用,我的项目代码里面是使用了方法调用方法自身去实现循环的。

就是这样的代码,供参考:

    public function watchJob()
    {
        $job = $this->pheanstalk->watch( config( &#39;tube&#39; ) )->ignore( &#39;default&#39; )->reserve();
        if ( $job !== false )
        {
            $job_data = $job->getData();
            $this->subscribe( $job_data );
            $this->pheanstalk->delete( $job );
            /* 继续 Watch 下一个 job */
            $this->watchJob();
        }
        else
        {
            $this->log->error( &#39;reserve false&#39;, &#39;reserve false&#39; );
        }
    }
Copy after login

监控 beanstalkd 状态

<?php
//监控服务状态
require_once(&#39;./vendor/autoload.php&#39;);
use Pheanstalk\Pheanstalk;
$pheanstalk = new Pheanstalk(&#39;127.0.0.1&#39;,11300);
$isAlive = $pheanstalk->getConnection()->isServiceListening();
var_dump( $isAlive );
Copy after login

可以配合 email 做一个报警邮件,脚本每分钟去执行,判断状态是 false,就给管理员发送邮件报警。

一些相关命令

查看 beanstalkd 服务内存占用

top -u beanstalkd
Copy after login

后台运行 consumer 脚本

nohup php googlehome_subscribe.php &
Copy after login

查看 consumer 脚本运行时间

ps -A -opid,stime,etime,args | grep consumer.php
Copy after login

手工重启 consumer 脚本

ps auxf|grep &#39;googlehome_subscribe.php&#39;|grep -v grep|awk &#39;{print $2}&#39;|xargs kill -9 
nohup php googlehome_subscribe.php &amp;
Copy after login

一些总结

  php 要把错误日志打开,方便收集 consumer 脚本 crash 的 log,脚本跑出一些致命的 error 一定要及时修复,因为一旦有错就会挂掉,这会影响你脚本的可用性,后期稳定之后可以上 supervisor 这种进程管理程序来管控脚本生命周期。

  一些网络请求操作,一定要 try catch 到所有错误,一旦没有 catch 到,脚本就崩。我用的是 Guzzle 去做的网络请求,下面是我 catch 的一些错误,代码片段供参考。

try
{
    /* TODO: 逻辑操作 */
}
catch ( ClientException $e )
{
    $results[&#39;mid&#39;]    = $this->mid;
    $results[&#39;code&#39;]   = $e->getResponse()->getStatusCode();
    $results[&#39;reason&#39;] = $e->getResponse()->getReasonPhrase();
    $this->log->error( &#39;properties-changed ClientException&#39;, $results );
}
catch ( ServerException $e )
{
    $results[&#39;mid&#39;]    = $this->mid;
    $results[&#39;code&#39;]   = $e->getResponse()->getStatusCode();
    $results[&#39;reason&#39;] = $e->getResponse()->getReasonPhrase();
    $this->log->error( &#39;properties-changed ServerException&#39;, $results );
}
catch ( ConnectException $e )
{
    $results[&#39;mid&#39;] = $this->mid;
    $this->log->error( &#39;properties-changed ConnectException&#39;, $results );
}
Copy after login

  job 消费之后一定要删除掉,如果长时间不删除,php 客户端会有 false 返回,是因为有 DEADLINE_SOON 这个超时错误产生,所以处理完任务,一定要记得删除,这一点跟 kafka 不一样,beanstalkd 需要开发者自己去删除 job。

推荐教程:《PHP教程

The above is the detailed content of PHP7 production environment queue Beanstalkd correct usage posture. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles