To dispatch jobs from one Laravel application to another using Redis, you need to ensure that both applications are configured to use the same Redis server and database for their queues. Here's a step-by-step guide to achieve this:
-
Ensure Network Access: Make sure that the Redis server is accessible from both servers. This might involve configuring your firewall to allow traffic on the Redis port (default is 6379) from the IP addresses of both servers.
-
Configure Redis in
database.php: In yourconfig/database.phpfile, set up a new Redis connection that points to the shared Redis server. For example:
'redis' => [
'client' => env('REDIS_CLIENT', 'predis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
// Add your new Redis connection here
'server2' => [
'host' => 'ip_of_the_other_server',
'password' => 'password_for_redis_on_other_server',
'port' => '6379',
'database' => '1', // Use a different database number if needed
],
],
-
Configure Queue Connection in
queue.php: In yourconfig/queue.phpfile, create a new queue connection that uses the Redis connection you just configured:
'connections' => [
// ... other queue connections ...
'redis-server2' => [
'driver' => 'redis',
'connection' => 'server2',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
- Dispatch the Job: When dispatching a job, specify the connection you want to use:
dispatch((new YourJob())->onConnection('redis-server2'));
Or, if you're using the dispatch function:
dispatch(new YourJob())->onConnection('redis-server2');
Make sure that:
- The Redis server is not bound to
127.0.0.1in its configuration file (redis.conf), as this will prevent external connections. It should be bound to0.0.0.0or the specific server IP that other servers can access. - The Redis server has a strong password if it's exposed to the internet or an untrusted network.
- Both Laravel applications have the same version of the job class, and the job class is compatible with the version of Laravel and PHP on both servers.
- The Horizon configurations on both servers are set up to monitor the correct queues.
If you've followed these steps and it's still not working, you may need to look into the following:
- Check the Laravel logs for any errors related to queue jobs.
- Use Redis monitoring tools or commands (
MONITORcommand in the Redis CLI) to see if the jobs are being pushed to the Redis server. - Ensure that the Horizon or queue worker on the second server is running and is not encountering any errors when processing jobs.
By following these steps, you should be able to dispatch jobs from one Laravel application to another using a shared Redis server.