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

Resque Laravel Package

amadeus-m/resque

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require amadeus-m/resque
    

    Enable the bundle in config/bundles.php:

    Amadeus\ResqueBundle\AmadeusResqueBundle::class => ['all' => true],
    
  2. Configuration: Add Redis connection details in config/packages/amadeus_resque.yaml:

    amadeus_resque:
        redis:
            host: '127.0.0.1'
            port: 6379
            password: null
        worker:
            count: 4
            log_file: '%kernel.logs_dir%/resque.log'
    
  3. First Job: Define a job class (e.g., src/Job/ProcessDataJob.php):

    namespace App\Job;
    
    use Resque\Job;
    
    class ProcessDataJob extends Job
    {
        protected $data;
    
        public function __construct($data)
        {
            $this->data = $data;
        }
    
        public function perform()
        {
            // Your logic here
            \Log::info('Processing data: ' . $this->data);
        }
    }
    
  4. Enqueue a Job: Use the Resque service in a controller or command:

    use Amadeus\ResqueBundle\Resque\Resque;
    
    class SomeController extends AbstractController
    {
        public function __invoke(Resque $resque)
        {
            $resque->enqueue('App\Job\ProcessDataJob', ['data' => 'example']);
        }
    }
    
  5. Run Workers: Start workers via CLI:

    php bin/console resque:work
    

Implementation Patterns

Common Workflows

  1. Job Dispatching:

    • Use dependency injection for Resque service in controllers, commands, or services.
    • Example in a service:
      public function __construct(private Resque $resque) {}
      
      public function queueTask($payload)
      {
          $this->resque->enqueue('App\Job\ProcessDataJob', $payload);
      }
      
  2. Delayed Jobs: Use delay method for scheduled execution:

    $resque->enqueue('App\Job\ProcessDataJob', ['data' => 'example'], 60); // Delay by 60 seconds
    
  3. Worker Management:

    • Scale workers dynamically via resque:work command with --count flag.
    • Use resque:restart to restart workers gracefully.
  4. Job Prioritization: Enqueue jobs with custom queues (e.g., high_priority):

    $resque->enqueue('App\Job\ProcessDataJob', ['data' => 'example'], 0, 'high_priority');
    
  5. Error Handling: Implement onFail in jobs for retries or logging:

    public function onFail($exception)
    {
        \Log::error('Job failed: ' . $exception->getMessage());
    }
    

Integration Tips

  1. Symfony Events: Trigger jobs from Symfony events (e.g., KernelEvents::TERMINATE):

    $eventDispatcher->addListener(KernelEvents::TERMINATE, function () use ($resque) {
        $resque->enqueue('App\Job\CleanupJob', []);
    });
    
  2. Doctrine Integration: Use jobs for async database operations (e.g., batch processing):

    public function processBatch($batchId)
    {
        $resque->enqueue('App\Job\BatchProcessJob', ['batch_id' => $batchId]);
    }
    
  3. Monitoring: Use Redis CLI or tools like resque-web (external) to monitor queues:

    redis-cli MONITOR
    
  4. Testing: Mock Resque service in PHPUnit:

    $this->mockBuilder()
        ->disableOriginalConstructor()
        ->getMock()
        ->method('enqueue')
        ->willReturn(true);
    

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues:

    • Ensure Redis server is running and accessible. Test with:
      redis-cli ping
      
    • Handle connection timeouts gracefully in production.
  2. Worker Stuck on Jobs:

    • Jobs may hang if they block indefinitely (e.g., no sleep() in loops).
    • Use Resque::pause() or Resque::kill() for stuck workers (via CLI or custom commands).
  3. Queue Locking:

    • Resque uses Redis locks. Avoid long-running jobs without proper timeouts.
    • Default timeout is 30 seconds; adjust in config/packages/amadeus_resque.yaml:
      amadeus_resque:
          worker:
              timeout: 120  # 2 minutes
      
  4. Job Serialization:

    • Complex objects (e.g., Doctrine entities) must implement Serializable or use __sleep()/__wakeup().
    • Example:
      public function __sleep()
      {
          return ['data'];
      }
      
  5. Worker Logs:

    • Logs are written to var/log/resque.log by default. Rotate logs in production:
      # config/packages/monolog.yaml
      handlers:
          resque:
              type: rotating_file
              path: '%kernel.logs_dir%/resque.log'
              max_files: 7
      

Debugging Tips

  1. Check Redis Queues:

    redis-cli LRANGE resque:queue 0 -1
    
  2. Worker Debugging:

    • Enable verbose output:
      php bin/console resque:work --verbose
      
    • Use STDERR logging for worker errors.
  3. Job Retries:

    • Failed jobs are moved to failed queue. Inspect with:
      redis-cli LRANGE resque:failed 0 -1
      
    • Requeue manually:
      php bin/console resque:requeue <job_class> <payload>
      
  4. Performance:

    • Monitor worker CPU/memory usage (htop or top).
    • Optimize job execution (e.g., batch processing, lazy loading).

Extension Points

  1. Custom Job Classes: Extend Resque\Job for shared logic:

    abstract class BaseJob extends Job
    {
        protected $logger;
    
        public function __construct()
        {
            $this->logger = new \Monolog\Logger('jobs');
        }
    
        protected function log($message)
        {
            $this->logger->info($message);
        }
    }
    
  2. Middleware: Use Resque::addMiddleware() to intercept jobs (e.g., logging, auth):

    $resque->addMiddleware(function ($job, $args) {
        \Log::info('Job dispatched: ' . get_class($job));
    });
    
  3. Custom Commands: Extend ResqueCommand for domain-specific tasks:

    namespace App\Command;
    
    use Amadeus\ResqueBundle\Command\ResqueCommand;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class CustomResqueCommand extends ResqueCommand
    {
        protected function configure()
        {
            $this->setName('app:resque:custom');
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $this->resque->enqueue('App\Job\CustomJob', ['data' => 'custom']);
            $output->writeln('Custom job queued!');
        }
    }
    
  4. Redis Configuration: Override Redis connection dynamically (e.g., per environment):

    # config/packages/amadeus_resque.yaml (prod)
    amadeus_resque:
        redis:
            host: '%env(REDIS_HOST)%'
            port: '%env(int:REDIS_PORT)%'
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui