定制 proilyxa/lara-thread 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

proilyxa/lara-thread

最新稳定版本:0.0.2

Composer 安装命令:

composer require proilyxa/lara-thread

包简介

This is my package lara-thread

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Description

Since Swoole 6 it supports multithreading, so it's a great way to speed up Laravel applications!

You can use this functionality in your Laravel Octane application if you are using the Swoole driver or in console commands.

Require: Laravel 10-11, php8.1+ ZTS (Thread safe), swoole 6.0+ extension which was compiled with the --enable-swoole-thread parameter

https://wiki.swoole.com/en/#/thread/thread

Installation

You can install the package via composer:

composer require proilyxa/lara-thread
php artisan vendor:publish --tag=proilyxa-lara-thread

Usage

public static function run(string $class, mixed ...$params): Thread

LaraThread::run takes as its first parameter a class that implements the run() method. The run method can have any input parameters.

Main

use Swoole\Thread\Queue;

$start = microtime(true);

$input = new Queue();
$output = new Queue();

$d = 20;
for ($i = 0; $i < $d; $i++) {
    $input->push('https://dog.ceo/api/breeds/image/random');
}

// create workers
$t = 5;
$threads = [];
for ($threadID = 0; $threadID < $t; $threadID++) {
    $threads[] = LaraThread::run(Run::class, $threadID + 1, $input, $output);
}

$result = [];
for ($i = 0; $i < $d; $i++) {
    $result[] = $output->pop(-1);
}

dump(LaraThread::recursiveUnserialize($result));

// waiting for threads to finish
for ($i = 0; $i < count($threads); $i++) {
    $threads[$i]->join();
}

echo 'timeline: ' . round(microtime(true) - $start, 4) . ' s.';

Worker

<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Support\Facades\Http;
use Swoole\Thread\ArrayList;
use Swoole\Thread\Map;
use Swoole\Thread\Queue;

class Run
{
    public function run(int $id, Queue $input, Queue $output): void
    {
        while (1) {
            $site = $input->pop();
            if ($site === null) {
                echo 'Thread: ' . $id . ' finished' . PHP_EOL;
                break;
            }
            $output->push(Http::get($site)->json(), Queue::NOTIFY_ONE);
            echo 'Thread: ' . $id . '  result pushed' . PHP_EOL;
        }
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

统计信息

  • 总下载量: 7
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-12-31