PHP code example of matheushasm / swoole-micro

1. Go to this page and download the library: Download matheushasm/swoole-micro library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

matheushasm / swoole-micro example snippets




use SwooleMicro\Queue\InMemoryQueueDriver;
use SwooleMicro\Supervisor\RedisSupervisor;

return [
    'queue' => [
        'driver' => InMemoryQueueDriver::class,
    ],

    'supervisor' => [
        'driver' => RedisSupervisor::class,
        'redis' => [
            'host' => getenv('REDIS_HOST') ?: '127.0.0.1',
            'port' => (int) (getenv('REDIS_PORT') ?: 6379),
            'prefix' => 'swoole-micro:',
        ],
    ],

    'workers' => [
        'emails' => [
            'processor' => \App\Processors\SendEmailProcessor::class,
            'queue' => 'emails',
            'options' => [
                'concurrency' => 10,
                'timeoutSeconds' => 30,
                'memoryLimitMb' => 256,
                'heartbeatSeconds' => 5,
            ],
        ],
    ],
];

interface ProcessorInterface
{
    public function handle(mixed $payload): void;
}



declare(strict_types=1);

namespace Examples\Processors;

use SwooleMicro\Core\ProcessorInterface;

final class SendEmailProcessor implements ProcessorInterface
{
    public function handle(mixed $payload): void
    {
        if (!is_array($payload) || empty($payload['to'])) {
            throw new \InvalidArgumentException('Invalid payload: missing "to".');
        }

        // Simulate I/O work
        \Swoole\Coroutine::sleep(0.1);

        echo sprintf("Email sent to %s\n", $payload['to']);
    }
}

$worker = Worker::make('emails')
    ->queue($queueDriver, 'emails')
    ->processor(new SendEmailProcessor())
    ->options(
        WorkerOptions::new()
            ->concurrency(10)
            ->timeoutSeconds(30)
            ->memoryLimitMb(256)
            ->heartbeatSeconds(5)
    )
    ->supervisor($redisSupervisor);

$worker->run();



declare(strict_types=1);

namespace App\Processors;

use SwooleMicro\Core\ProcessorInterface;

final class SendEmailProcessor implements ProcessorInterface
{
    public function handle(mixed $payload): void
    {
        if (!is_array($payload) || empty($payload['to'])) {
            throw new \InvalidArgumentException('Invalid payload: missing "to".');
        }

        \Swoole\Coroutine::sleep(0.1);
        echo sprintf("Email sent to %s\n", $payload['to']);
    }
}



use SwooleMicro\Queue\RedisQueueDriver;
use SwooleMicro\Supervisor\RedisSupervisor;

return [
    'queue' => [
        'driver' => RedisQueueDriver::class,
        'redis' => [
            'host' => '127.0.0.1',
            'port' => 6379,
            'db' => 0,
            'username' => 'default',
            'password' => '',
            'prefix' => 'swoole-micro:',
        ],
    ],
    'supervisor' => [
        'driver' => RedisSupervisor::class,
        'redis' => [
            'host' => '127.0.0.1',
            'port' => 6379,
            'db' => 0,
            'username' => 'default',
            'password' => '',
            'prefix' => 'swoole-micro:',
        ],
    ],
    'workers' => [
        'emails' => [
            'processor' => \App\Processors\SendEmailProcessor::class,
            'queue' => 'emails',
            'options' => [
                'concurrency' => 10,
                'timeoutSeconds' => 30,
                'memoryLimitMb' => 256,
                'heartbeatSeconds' => 5,
            ],
        ],
    ],
];

$items = range(1, 100);

CoroutinePool::make()
    ->maxConcurrency(20)
    ->run($items, function (int $item): void {
        // Simulate I/O
        \Swoole\Coroutine::sleep(0.05);
        echo "Processed item: {$item}\n";
    });

public function handle(mixed $payload): void
{
    $urls = $payload['urls'] ?? [];

    \\SwooleMicro\\Core\\CoroutinePool::make()
        ->maxConcurrency(10)
        ->run($urls, function (string $url): void {
            \\Swoole\\Coroutine::sleep(0.05);
            echo \"Fetched {$url}\\n\";
        });
}

use SwooleMicro\Core\BatchProcessor;

final class FetchUrlsProcessor extends BatchProcessor
{
    protected function maxConcurrency(mixed $payload): int
    {
        return 10;
    }

    protected function itemsFromPayload(mixed $payload): array
    {
        return is_array($payload) && isset($payload['urls']) ? $payload['urls'] : [];
    }

    protected function processItem(mixed $item, mixed $payload): void
    {
        \Swoole\Coroutine::sleep(0.05);
        echo "Fetched {$item}\n";
    }
}

(new FetchUrlsProcessor())
    ->concurrency(10)
    ->handle(['urls' => ['https://example.com']]);

$supervisor->heartbeat($workerName, $instanceId);

$dead = $supervisor->deadWorkers($thresholdSeconds = 15);

foreach ($dead as $deadWorker) {
    echo "DEAD: {$deadWorker}\n";
}

swoole-micro/
├── bin/
│   └── swoole-micro
├── config/
│   └── workers.php
├── src/
│   ├── Core/
│   │   ├── ProcessorInterface.php
│   │   ├── Worker.php
│   │   ├── WorkerOptions.php
│   │   ├── CoroutinePool.php
│   │   ├── Exceptions/
│   │   │   ├── ProcessorFailed.php
│   │   │   └── WorkerCrashed.php
│   ├── Queue/
│   │   ├── QueueDriverInterface.php
│   │   └── InMemoryQueueDriver.php
│   ├── Supervisor/
│   │   ├── SupervisorInterface.php
│   │   └── RedisSupervisor.php
│   └── Support/
│       ├── Env.php
│       └── Json.php
├── examples/
│   ├── processors/
│   │   ├── SendEmailProcessor.php
│   │   └── FetchUrlsProcessor.php
│   └── run_examples.php
├── tests/
├── composer.json
├── README.md
└── LICENSE

sudo apt update
sudo apt install -y php-cli php-dev php-pear php-curl php-mbstring php-xml pkg-config redis-server
sudo pecl install swoole redis
echo "extension=swoole" | sudo tee /etc/php/8.2/cli/conf.d/20-swoole.ini
echo "extension=redis" | sudo tee /etc/php/8.2/cli/conf.d/20-redis.ini

brew install [email protected] pkg-config pcre2
brew install redis
pecl install swoole redis
echo "extension=swoole" > /opt/homebrew/etc/php/8.4/conf.d/ext-swoole.ini
echo "extension=redis" > /opt/homebrew/etc/php/8.4/conf.d/ext-redis.ini
brew services restart php

sudo apt update
sudo apt install -y php-cli php-dev php-pear php-curl php-mbstring php-xml pkg-config redis-server
sudo pecl install swoole redis
echo "extension=swoole" | sudo tee /etc/php/8.2/cli/conf.d/20-swoole.ini
echo "extension=redis" | sudo tee /etc/php/8.2/cli/conf.d/20-redis.ini
dockerfile
FROM php:8.2-cli

RUN apt-get update && apt-get install -y \\
    git unzip pkg-config libssl-dev libcurl4-openssl-dev \\
    libbrotli-dev libzstd-dev libpcre2-dev \\
    && pecl install swoole redis \\
    && docker-php-ext-enable swoole redis

WORKDIR /app
COPY . /app
RUN composer install

CMD [\"php\", \"bin/swoole-micro\", \"worker:run\", \"default\"]

php bin/swoole-micro worker:run emails

php bin/swoole-micro worker:run emails 4

php bin/swoole-micro supervisor:watch

php bin/swoole-micro

php bin/swoole-micro workers:list
php bin/swoole-micro worker:run default
php bin/swoole-micro worker:run default 4
php bin/swoole-micro worker:run default --instances=4
php bin/swoole-micro worker:spawn default 3
php bin/swoole-micro queue:push default '{"to":"[email protected]"}'
php bin/swoole-micro supervisor:watch

php bin/swoole-micro worker:run emails --instances=4