Search code examples
redispublish-subscribe

Event-based mailing with Redis, Python and PHP


I want to frequently publish messages to a Redis server from a Python component. Then, in an other PHP component that also has the access to this Redis server, I want to send emails to users based on the messages that are stored in Redis. If I'm not wrong, there are two ways of doing that: Push-Pull and Push-Push designs:

Pull design

The PHP component is frequently making requests to the Redis server, and when there is a new message, make the action.

Push design:

We don't need to make these frequent requests from the PHP component: Whenever a new message is published in Redis, the action from the PHP component can be triggered.

My question

How can we implement the Push-Push design? When I read the Redis documentation about the Pub-Sub model, I don't find anything about it. So I don't really understand how we can trigger an action, in an other way then making frequent requests to the redis server.


Solution

  • You need to run a "long-running" php process as daemon via using solutions such as nohup, supervisor or upstart. This process will keep working as daemon to consume your redis channel. Python will keep producing, php will keep consuming.

    There are several libraries to run php process as daemon such as reactphp or if you are using a framework such as laravel, it offers a good pub/sub interface.

    It will be something like this;

    Php part will subscribe to mychannel

    127.0.0.1:6379> SUBSCRIBE mychannel
    Reading messages... (press Ctrl-C to quit)
    1) "subscribe"
    2) "mychannel"
    3) (integer) 1
    

    python will publish to mychannel

    127.0.0.1:6379> publish mychannel myemailjson
    (integer) 1
    127.0.0.1:6379> publish mychannel myanotheremailjson
    (integer) 1
    127.0.0.1:6379>
    

    in the meanwhile, your php process will receive that messages

    1) "message"
    2) "mychannel"
    3) "myemailjson"
    1) "message"
    2) "mychannel"
    3) "myanotheremailjson"
    

    In that subscriber php process you will call/trigger/dispatch your email delivery jobs(probably asynchronously) whenever it receives a message.