Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gearman Laravel Package

enqueue/gearman

Gearman transport for Enqueue: send and consume queue messages via a Gearman broker using Enqueue’s queue specification. Part of the php-enqueue ecosystem with docs, support chat, and CI-tested releases.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:

    composer require enqueue/gearman enqueue/laravel enqueue/doctrine
    
    • enqueue/gearman: Gearman transport.
    • enqueue/laravel: Laravel bridge for Enqueue.
    • enqueue/doctrine (optional): For Doctrine integration if using ORM.
  2. Configure Laravel: Add Gearman connection to config/queue.php:

    'connections' => [
        'gearman' => [
            'driver' => 'enqueue',
            'transport' => 'gearman',
            'host' => env('GEARMAN_HOST', '127.0.0.1'),
            'port' => env('GEARMAN_PORT', 4730),
            'timeout' => 5.0, // Gearman connection timeout
        ],
    ],
    
  3. Dispatch a Job:

    use App\Jobs\ProcessPodcast;
    use Illuminate\Support\Facades\Queue;
    
    Queue::connection('gearman')->push(new ProcessPodcast());
    
  4. Run Gearman Worker: Start a Gearman worker process (e.g., via gearman-worker CLI or a PHP script):

    gearman-worker --job-background --queue-max-jobs=1000 --queue-timeout=60
    

    Or programmatically:

    $context = new \Enqueue\Client\Context();
    $consumer = new \Enqueue\Gearman\Consumer($context, ['host' => '127.0.0.1']);
    $consumer->setJobHandler(new \App\Jobs\GearmanJobHandler());
    $consumer->run();
    
  5. Verify Job Handling: Ensure the job appears in Gearman’s queue and is processed by the worker.


Implementation Patterns

Core Workflows

1. Job Dispatching

  • Laravel Jobs: Use Laravel’s Queue facade with the Gearman connection:
    Queue::connection('gearman')->later(now()->addMinutes(5), new SendEmailJob($user));
    
  • Raw Messages: For non-Laravel jobs, use Enqueue’s Producer:
    $producer = new \Enqueue\Gearman\Producer($context, ['host' => 'gearman']);
    $producer->send(new \Enqueue\Message\Message('task_name', json_encode($data)));
    

2. Job Consumption

  • Worker Script: Create a PHP script to consume jobs (e.g., artisan gearman:work):
    $consumer = new \Enqueue\Gearman\Consumer($context, ['host' => 'gearman']);
    $consumer->setJobHandler(new class implements \Enqueue\Client\JobHandler {
        public function handle(\Enqueue\Client\Job $job) {
            $data = json_decode($job->getData(), true);
            // Process job...
            return new \Enqueue\Client\Result(200, ['status' => 'done']);
        }
    });
    $consumer->run();
    
  • Laravel Job Handling: Extend Illuminate\Bus\Queueable and implement handle():
    class ProcessPodcast implements ShouldQueue {
        public function handle() {
            // Job logic
        }
    }
    

3. Connection Management

  • Dynamic Connections: Use Enqueue’s ConnectionFactory to switch transports at runtime:
    $factory = new \Enqueue\Client\ConnectionFactory();
    $connection = $factory->createConnection(['transport' => 'gearman', 'host' => 'gearman']);
    $producer = new \Enqueue\Gearman\Producer($connection);
    

4. Error Handling

  • Retry Logic: Configure retries in Laravel’s App\Exceptions\Handler:
    public function register()
    {
        $this->registerQueueShouldBeUnique();
        $this->registerQueueAfterCommit();
        $this->registerQueueFailed();
    }
    
  • Gearman-Specific Errors: Catch Enqueue\Transport\Exception\TimeoutException for connection issues:
    try {
        $producer->send($message);
    } catch (\Enqueue\Transport\Exception\TimeoutException $e) {
        Log::error('Gearman timeout: ' . $e->getMessage());
        // Fallback to another queue
    }
    

5. Scaling Workers

  • Horizontal Scaling: Deploy multiple Gearman workers (e.g., via Docker or Kubernetes) with unique job queues:
    gearman-worker --queue-name=worker1 --job-background
    gearman-worker --queue-name=worker2 --job-background
    
  • Load Balancing: Use Gearman’s --queue-max-jobs and --queue-timeout flags to distribute load.

Integration Tips

Laravel-Specific

  1. Queue Middleware: Use Laravel’s queue middleware (e.g., throttle, timeout) with Gearman:

    Queue::connection('gearman')->push(new Job)->throttle(5);
    
  2. Job Events: Listen to job.processing, job.processed, and job.failed events:

    event(new JobProcessed($job));
    
  3. Queue Monitoring: Use Laravel’s queue:failed and queue:work commands:

    php artisan queue:work --queue=gearman --sleep=3 --tries=3
    

Gearman-Specific

  1. Worker Prioritization: Use Gearman’s --priority flag to prioritize critical jobs:

    gearman-worker --priority=high --queue-name=critical
    
  2. Job Timeouts: Set timeouts in the producer:

$producer->send($message, ['timeout' => 30]); // 30-second timeout


3. **Background Jobs**:
 Run workers in detached mode:
 ```bash
 gearman-worker --job-background --detach

Performance

  1. Batch Processing: Use Gearman’s --queue-max-jobs to limit concurrent jobs:

    gearman-worker --queue-max-jobs=50
    
  2. Connection Pooling: Reuse Producer and Consumer instances to avoid connection overhead:

    $producer = new \Enqueue\Gearman\Producer($context, ['host' => 'gearman']);
    // Reuse $producer for multiple sends
    
  3. Async Dispatch: Dispatch jobs asynchronously to avoid blocking HTTP requests:

    Queue::connection('gearman')->push(new LongRunningJob)->onConnection('gearman');
    

Gotchas and Tips

Pitfalls

  1. No Active Maintenance:

    • The package is unmaintained (last release: 2017). Test thoroughly with newer PHP/Laravel versions.
    • Workaround: Fork the repository and update dependencies (e.g., enqueue/enqueue compatibility).
  2. Gearman Protocol Limitations:

    • No native delayed jobs: Use Laravel’s Queue::later() with a fallback to database queue if Gearman fails.
    • No built-in retries: Implement custom retry logic in job handlers or use Laravel’s retryAfter().
    • No job priority: Gearman’s priority is worker-level, not per-job. Use separate queues for priority jobs.
  3. Connection Issues:

    • Gearman connections can hang or time out. Set reasonable timeouts:
      'timeout' => 10.0, // Increase if jobs are slow
      
    • Workaround: Use a connection pool or retry logic for transient failures.
  4. Serialization Quirks:

    • Gearman does not support PHP objects directly. Ensure jobs are serializable:
      class MyJob implements ShouldQueue, JsonSerializable {
          public function toArray() { return ['data' => $this->data]; }
      }
      
    • Gotcha: Avoid circular references in job payloads.
  5. Worker Crashes:

    • Gearman workers do not auto-restart on failure. Use a process manager (e.g., Supervisor) or Kubernetes liveness probes:
      [program:gearman-worker]
      command=gearman-worker --job-background
      autorestart=true
      
  6. Laravel Queue Events:

    • Gearman does not fire Laravel’s queue events (job.processing, etc.) by default. Use Enqueue’s event system:
      $context->getEventDispatcher()->addListener(\Enqueue\Client\Event\JobProcessed::class, function ($event) {
          event(new JobProcessed($event->getJob()));
      });
      
  7. Docker Networking:

    • Gearman requires direct host:port access.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor