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

Php Resque Laravel Package

chrisboulton/php-resque

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chrisboulton/php-resque
    

    Ensure Redis is running locally or on your server (Resque requires Redis as a backend).

  2. Basic Configuration Create a Redis connection in config/database.php (if not using Laravel's default Redis):

    'redis' => [
        'client' => 'predis',
        'options' => [
            'scheme' => 'tcp',
            'host' => '127.0.0.1',
            'port' => 6379,
        ],
    ],
    

    Configure Resque in config/resque.php (if using Laravel's config publishing):

    php artisan vendor:publish --provider="Chrisboulton\Resque\ResqueServiceProvider"
    

    Update the published config with your Redis connection name (e.g., 'connection' => 'redis').

  3. First Job Define a job class:

    namespace App\Jobs;
    
    use Chrisboulton\Resque\Job\Job as ResqueJob;
    
    class ProcessUser extends ResqueJob
    {
        protected $userId;
    
        public function __construct($userId)
        {
            $this->userId = $userId;
        }
    
        public function perform()
        {
            // Your logic here (e.g., send email, process data)
            \Log::info("Processing user {$this->userId}");
        }
    }
    
  4. Enqueue a Job

    use App\Jobs\ProcessUser;
    use Chrisboulton\Resque\Facades\Resque;
    
    Resque::enqueue(new ProcessUser(1));
    
  5. Run a Worker

    php artisan resque:work queue:*
    

    (Replace queue:* with a specific queue name if needed.)


Implementation Patterns

Job Design Patterns

  1. Dependency Injection Use constructor injection for job dependencies (e.g., repositories, services):

    class SendWelcomeEmail extends ResqueJob
    {
        protected $user;
        protected $mailer;
    
        public function __construct(User $user, Mailer $mailer)
        {
            $this->user = $user;
            $this->mailer = $mailer;
        }
    
        public function perform()
        {
            $this->mailer->send('welcome', [], $this->user->email);
        }
    }
    

    Enqueue with bound dependencies:

    Resque::enqueue(new SendWelcomeEmail($user, app(Mailer::class)));
    
  2. Chaining Jobs Use after or then to chain jobs (requires custom implementation or middleware):

    Resque::enqueue(new ProcessUser(1))
        ->after(function () {
            Resque::enqueue(new NotifyUser(1));
        });
    

    Alternative: Use a parent job class with perform() logic that enqueues follow-up jobs.

  3. Delayed Jobs Delay execution using delay:

    Resque::enqueue(new ProcessUser(1))->delay(60); // 60 seconds
    
  4. Job Prioritization Use multiple queues (e.g., high, default, low) and process them in order:

    php artisan resque:work high,default,low
    

    Enqueue to a specific queue:

    Resque::enqueue(new ProcessUser(1), 'high');
    

Worker Management

  1. Horizontal Scaling Run multiple workers (e.g., one per core) to parallelize processing:

    php artisan resque:work queue:* --daemon --pidfile=/tmp/resque.pid
    

    Use --daemon for background operation and --pidfile for process management.

  2. Queue Monitoring Check queue status with:

    php artisan resque:status
    

    List all jobs in a queue:

    php artisan resque:list queue:high
    
  3. Worker Events Listen to worker lifecycle events (e.g., job started/failed) via events:

    // In EventServiceProvider
    protected $listen = [
        'Chrisboulton\Resque\Events\JobStarted' => [
            'App\Listeners\LogJobStart',
        ],
        'Chrisboulton\Resque\Events\JobFailed' => [
            'App\Listeners\NotifyOnFailure',
        ],
    ];
    
  4. Retry Logic Implement retry() in your job to handle failures:

    public function perform()
    {
        try {
            // Risky operation
        } catch (\Exception $e) {
            $this->retry(3); // Retry up to 3 times
            throw $e;
        }
    }
    

Integration with Laravel

  1. Queue Connection Bind Resque to Laravel's queue system in AppServiceProvider:

    public function boot()
    {
        Queue::extend('resque', function ($app) {
            return new ResqueQueueService($app);
        });
    }
    

    Then use Laravel's queue helpers:

    dispatch(new ProcessUser(1))->onQueue('resque');
    
  2. Job Serialization Ensure job classes are serializable (avoid closures or non-serializable properties). Use __serialize()/__unserialize() if needed:

    public function __serialize()
    {
        return ['userId' => $this->userId];
    }
    
    public function __unserialize(array $data)
    {
        $this->userId = $data['userId'];
    }
    
  3. Laravel Events as Jobs Convert Laravel events to async jobs:

    // In EventServiceProvider
    protected $listen = [
        'user.created' => [
            function (User $user) {
                Resque::enqueue(new ProcessUser($user->id));
            },
        ],
    ];
    

Gotchas and Tips

Common Pitfalls

  1. Redis Connection Issues

    • Symptom: Workers fail silently or jobs disappear.
    • Fix: Verify Redis is running and the Laravel Redis config matches the Resque config. Use php artisan resque:status to debug.
    • Tip: Enable Redis logging to trace connection drops:
      redis-cli monitor
      
  2. Job Serialization Errors

    • Symptom: Jobs fail with Unable to serialize job or Class not found.
    • Fix: Ensure all job dependencies are serializable. Avoid:
      • Closures or anonymous functions.
      • Non-serializable objects (e.g., database connections, open file handles).
    • Tip: Use __serialize()/__unserialize() for complex objects.
  3. Worker Stuck in "Working" State

    • Symptom: Jobs appear stuck in the queue, and workers show as "working" indefinitely.
    • Fix: Kill stuck workers (kill -9 <PID>) and re-enqueue failed jobs. Use --timeout to limit worker runtime:
      php artisan resque:work queue:* --timeout=300
      
  4. Race Conditions

    • Symptom: Jobs process the same data multiple times or conflict with each other.
    • Fix: Use Redis locks or database transactions:
      public function perform()
      {
          if (Redis::lock("process_user_{$this->userId}", 10)) {
              try {
                  // Critical section
              } finally {
                  Redis::unlock("process_user_{$this->userId}");
              }
          }
      }
      
  5. Memory Leaks

    • Symptom: Workers crash with Allowed memory size exhausted.
    • Fix: Limit job execution time and memory usage:
      • Set max_execution_time in php.ini or per-worker:
        php artisan resque:work queue:* --max-execution-time=300
        
      • Use memory_get_usage() to monitor memory in jobs.

Debugging Tips

  1. Worker Logging Enable verbose logging for workers:

    php artisan resque:work queue:* --verbose
    

    Or configure logging in config/resque.php:

    'log' => [
        'enabled' => true,
        'path' => storage_path('logs/resque.log'),
    ],
    
  2. Job Inspection Dump job payloads for debugging:

    public function perform()
    {
        \Log::debug('Job payload:', [
            'userId' => $this->userId,
            'args' => func_get_args(),
        ]);
    }
    
  3. Redis Debugging Inspect queues directly:

    redis-cli LRANGE resque:queue:high 0 -1
    redis-cli HGETALL resque:job:high:<job_id>
    
  4. Worker PID Management Use --pidfile to manage

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware