国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
How to use message queue queue and asynchronous queue in PHP's Laravel framework, laravelqueue
您可能感興趣的文章:
Home Backend Development PHP Tutorial How to use message queue queue and asynchronous queue in PHP's Laravel framework, laravelqueue_PHP tutorial

How to use message queue queue and asynchronous queue in PHP's Laravel framework, laravelqueue_PHP tutorial

Jul 12, 2016 am 08:56 AM
laravel php message queue

How to use message queue queue and asynchronous queue in PHP's Laravel framework, laravelqueue

queue configuration

First, let me explain how to use queue in my previous project.

Our current projects all use symfony, older projects use symfony1.4, and newer projects use symfony2. The overall feeling of using symfony is very pleasant, especially symfony2, which generally uses a lot of design ideas from Java frameworks. But it does not support queue. In symfony, we have also gone through several processes using queue. I first used Zhang Yan’s httpsqs. This one is simple to use, but has a single point. After all, our project is still officially for external services, so we studied ActiveMQ, an open source project under Apache, and found that there is a newer MQ under Apache, which is Apollo. In the end we decided to use Apollo.

The main application scenario of queue in our project is to asynchronously process some time-consuming functions, such as synchronizing third-party data, synchronously notifying our third-party data users of data changes, etc. Our general idea is this. If asynchronous processing is needed in each controller, just encode a json object and stuff it into Apollo. Write another work Command, parse the json object in this Command, and call different methods based on the actions and parameters inside. Running Command as a daemon process on different machines at the same time according to business needs can also be considered as a solution to implement asynchronous multi-tasking applications. I kept using it until I discovered laravel. Plan to research it. It's not impossible to replace it if possible. hehe.

Since I just started learning, of course I went straight to laravel5. Routes, controllers, and views are basically the same as symfony, so it’s not difficult to get started. Finally, study the queue.

1. Installing laravle and using composer is very simple.

composer global require "laravel/installer=~1.1"
vi ~/.bash_profile

Add ~/.composer/vendor/bin to the environment variables.

source ~/.bash_profile

You can use laravel directly from the command line. Give it a try.

laravel -V

If you can see the following, it means success.

Laravel Installer version 1.2.1

2. Create a project.

laravel new guagua

3. Configure redis and queue.

4. Create controller,

php artisan make:controller DefaultController

Push 100 queue tasks in the controller's action.

for($i = 0; $i < 100; $i ++) {
  Queue::push(new SendEmail("ssss".$i));
}

5. Command to create queue

php artisan make:command SendEmail --queued

Modify app/Commands/SendEmail.php and add a private variable.

protected $msg;

Also modify the constructor.

public function __construct($msg)
{
  $this->msg = $msg;
}

Modified handle method

public function handle() {
  sleep(4);
  echo $this->msg."\t".date("Y-m-d H:i:s")."\n";
  $this->delete();
}

6. Modify routes

Route::get('/', [
  'as' => 'index',
  'uses' => 'DefaultController@index'
]);

7. Monitor queue

php artisan queue:listen

To verify multitasking, we opened three windows at the same time and ran the same command.

8. Start the service using laravel’s built-in server

php artisan serve --port 8080 

Open the browser and visit the http://localhost:8080/ page. Of course, you can also use nginx, apache, etc. However, various configurations are required, and the built-in ones are easy to use.

You can see the execution status of each queue in the console, as shown below. You can see that 100 tasks are divided equally among three jobs.

2016321142239283.png (862×658)

At this point, I have basically achieved the effect I wanted. It is verified that laravel can easily implement queue and can handle multi-tasking.

use AppCommandsCommand is used in the code generated by make command, but when running, it prompts that there is no such file. The solution is to change it to use IlluminateConsoleCommand; I don’t know why this low-level problem occurs. Is it a problem with my mac system or a problem with my character?
When pushing the queue in the controller's action, there is no asynchronous execution, and it is still executed in the action's script. It was found that it was a configuration problem. It turned out that not only queue.php in config must be modified, but also related configurations in .evn must be modified. Although the problem has been solved, I still feel pain in my balls and cannot understand it. Still need to learn laravel.

How to use asynchronous queue

1. Configuration

The definition of queue will not be introduced here. There are two keys to using asynchronous queues:

(1) Where to store queues
(2) Services that perform tasks
Open config/queue.php, which is Laravel5’s queue configuration file. First, we can specify the default queue driver through the default parameter. The default configuration is sync, which is a synchronous queue. To make an asynchronous queue, we must first change this. Assuming we use database as the driver, the queue tasks will be stored in the database, and we will start another background service to process the queue tasks later. This is the asynchronous method.

'default' => 'database'

After modifying the configuration, we need to create a table to store the queue tasks. Laravel5 has a built-in instruction in the artisan command to generate data migration. It only requires two commands. Of course, you must implement the configuration. Database connection.

php artisan queue:table
php artisan migrate

This automatically creates the jobs table in the database.

2. Start the queue listening service

通過下面這條指令啟動隊列監(jiān)聽服務(wù),它會自動處理 jobs 表中的隊列任務(wù):

php artisan queue:listen

在linux中,如果想讓它在后臺執(zhí)行,可以這樣:

nohup php artisan queue:listen &

3.添加隊列任務(wù)

關(guān)于隊列任務(wù)的添加,手冊里說的比較詳細,這里就簡單舉個例子吧。

首先,通過artisan創(chuàng)建一個隊列命令:

php artisan make:command SendEmail --queued

這樣會生成 app/Commands/SendEmail.php 這個類文件,這個類會被標識為隊列命令,你可以在 handle 方法中寫自己的業(yè)務(wù)邏輯。

在控制器中,可以簡單通過 Bus::dispatch 分發(fā)任務(wù):

Bus::dispatch(new \App\Commands\SendEmail());

你會發(fā)現(xiàn)任務(wù)不會立即執(zhí)行,而是被放到 jobs 表中,由隊列監(jiān)聽服務(wù)處理。

更詳細的用法建議參考 command bus 和 queue 相關(guān)的手冊章節(jié)。

您可能感興趣的文章:

  • 深入解析PHP的Laravel框架中的event事件操作
  • PHP的Laravel框架結(jié)合MySQL與Redis數(shù)據(jù)庫的使用部署
  • 詳解PHP的Laravel框架中Eloquent對象關(guān)系映射使用
  • PHP框架Laravel學(xué)習(xí)心得體會
  • 全面解讀PHP的人氣開發(fā)框架Laravel
  • Nginx中運行PHP框架Laravel的配置文件分享
  • PHP IDE PHPStorm配置支持友好Laravel代碼提示方法
  • 使用 PHPStorm 開發(fā) Laravel
  • PHP開發(fā)框架laravel安裝與配置教程
  • PHP框架Laravel的小技巧兩則
  • PHP的Laravel框架中使用AdminLTE模板來編寫網(wǎng)站后臺

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1113734.htmlTechArticlePHP的Laravel框架中使用消息隊列queue及異步隊列的方法,laravelqueue queue配置 首先說明一下我之前的項目中如何使用queue的。 我們現(xiàn)在的項目都...
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

how to avoid undefined index error in PHP how to avoid undefined index error in PHP Jul 14, 2025 am 02:51 AM

There are three key ways to avoid the "undefinedindex" error: First, use isset() to check whether the array key exists and ensure that the value is not null, which is suitable for most common scenarios; second, use array_key_exists() to only determine whether the key exists, which is suitable for situations where the key does not exist and the value is null; finally, use the empty merge operator?? (PHP7) to concisely set the default value, which is recommended for modern PHP projects, and pay attention to the spelling of form field names, use extract() carefully, and check the array is not empty before traversing to further avoid risks.

PHP prepared statement with IN clause PHP prepared statement with IN clause Jul 14, 2025 am 02:56 AM

When using PHP preprocessing statements to execute queries with IN clauses, 1. Dynamically generate placeholders according to the length of the array; 2. When using PDO, you can directly pass in the array, and use array_values to ensure continuous indexes; 3. When using mysqli, you need to construct type strings and bind parameters, pay attention to the way of expanding the array and version compatibility; 4. Avoid splicing SQL, processing empty arrays, and ensuring data types match. The specific method is: first use implode and array_fill to generate placeholders, and then bind parameters according to the extended characteristics to safely execute IN queries.

Choosing between Laravel Sanctum and Passport for API authentication Choosing between Laravel Sanctum and Passport for API authentication Jul 14, 2025 am 02:35 AM

LaravelSanctum is suitable for simple, lightweight API certifications such as SPA or mobile applications, while Passport is suitable for scenarios where full OAuth2 functionality is required. 1. Sanctum provides token-based authentication, suitable for first-party clients; 2. Passport supports complex processes such as authorization codes and client credentials, suitable for third-party developers to access; 3. Sanctum installation and configuration are simpler and maintenance costs are low; 4. Passport functions are comprehensive but configuration is complex, suitable for platforms that require fine permission control. When selecting, you should determine whether the OAuth2 feature is required based on the project requirements.

PHP check if a string starts with a specific string PHP check if a string starts with a specific string Jul 14, 2025 am 02:44 AM

In PHP, you can use a variety of methods to determine whether a string starts with a specific string: 1. Use strncmp() to compare the first n characters. If 0 is returned, the beginning matches and is not case sensitive; 2. Use strpos() to check whether the substring position is 0, which is case sensitive. Stripos() can be used instead to achieve case insensitive; 3. You can encapsulate the startsWith() or str_starts_with() function to improve reusability; in addition, it is necessary to note that empty strings return true by default, encoding compatibility and performance differences, strncmp() is usually more efficient.

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

See all articles