PHP code example of yangusik / laravel-balanced-queue
1. Go to this page and download the library: Download yangusik/laravel-balanced-queue 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/ */
yangusik / laravel-balanced-queue example snippets
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use YanGusik\BalancedQueue\Jobs\BalancedDispatchable;
class GenerateAIImage implements ShouldQueue
{
use BalancedDispatchable; // Instead of standard Dispatchable
public function __construct(
public int $userId,
public string $prompt
) {}
public function handle(): void
{
// Your AI generation logic here
}
}
// The job will automatically use $userId as partition key
GenerateAIImage::dispatch($userId, $prompt)
->onConnection('balanced')
->onQueue('ai-generation');
// Or explicitly set partition
GenerateAIImage::dispatch($userId, $prompt)
->onPartition($userId)
->onConnection('balanced');
'environments' => [
'local' => [
// Your other supervisors...
'supervisor-balanced' => [
'connection' => 'balanced', // Must match connection name in queue.php
'queue' => ['default'], // Queue names to process
'maxProcesses' => 4, // Number of workers
'tries' => 1,
'timeout' => 300,
],
],
'production' => [
'supervisor-balanced' => [
'connection' => 'balanced',
'queue' => ['default', 'ai-generation'],
'maxProcesses' => 10,
'tries' => 1,
'timeout' => 300,
'balance' => 'auto', // Horizon's auto-scaling
],
],
],
// config/balanced-queue.php
'limiter' => env('BALANCED_QUEUE_LIMITER', 'simple'),
'limiters' => [
'simple' => [
'max_concurrent' => 2, // Max 2 jobs per user at once
],
],
class MyJob implements ShouldQueue
{
use BalancedDispatchable;
public function __construct(
public int $userId // Automatically used as partition key
) {}
}
// Set partition when dispatching
MyJob::dispatch($data)
->onPartition("user:{$userId}")
->onConnection('balanced');
// Or set in job constructor
MyJob::dispatch($data)
->onPartition($companyId)
->onConnection('balanced');
class ProcessOrder implements ShouldQueue
{
use BalancedDispatchable;
public function __construct(public Order $order) {}
public function getPartitionKey(): string
{
// Partition by merchant instead of user
return "merchant:{$this->order->merchant_id}";
}
}
use YanGusik\BalancedQueue\Contracts\PartitionStrategy;
use Illuminate\Contracts\Redis\Connection;
class PriorityStrategy implements PartitionStrategy
{
public function selectPartition(Connection $redis, string $queue, string $partitionsKey): ?string
{
// Get all partitions
$partitions = $redis->smembers($partitionsKey);
// Your priority logic here
// e.g., check user subscription level, queue size, etc.
return $selectedPartition;
}
public function getName(): string
{
return 'priority';
}
}