Since version 2.6, Redis can evaluate scripts written in Lua with the EVAL command. I had to write a Lua script to be able to publish the same message to multiple channels (Pub/Sub).
Using a pipeline/transaction would be very inefficient depending on the size of the message, so it's quicker and more efficient to write a custom script. And I couldn't use PSUBSCRIBE in my use case.
Here is the Lua script that allow to publish the same message to multiple channels at once:
local res = {}
for i = 2, #ARGV do
table.insert(res, redis.call('publish', ARGV[i], ARGV[1]))
end
return res
You can use Lua scripting with any Redis client, an example using Python and redis:
>>> import redis
>>> r = redis.StrictRedis()
>>> lua = """
... local res = {}
... for i = 2, #ARGV do
... table.insert(res, redis.call('publish', ARGV[i], ARGV[1]))
... end
... return res
... """
>>> multipublish = r.register_script(lua)
>>> multipublish(args=["message", "channel1", "channel2", "channel3"])
[1L, 0L, 0L]
Your feedback
Please don't hesitate if you have any feedback/question/suggestion !
Tip with Bitcoin
Tip me with Bitcoin and vote for this post!
Leave a comment