Redis Lua Scripting
Redis Lua Scripting for Transactions in PHP
Welcome! In this lesson, we're exploring a powerful feature: **Lua scripting **. Using Lua scripts in Redis provides a robust method for ensuring the atomic execution of non trivial operations. This means you can bundle multiple Redis commands into a single script, ensuring they execute together without interruption.
Here's a code example demonstrating how you might use a Lua script:
In the code above, we execute a Lua script atomically, ensuring all operations are performed together. We also handle potential errors during script execution with the try/catch block.
In the code row $newCount = $client->eval($luaScript, 1, 'counter', 5);, the eval method is called to execute a Lua script on the Redis server. Here's a breakdown of the parameters provided in the eval call:
-
$luaScript: This parameter passes the Lua script code to theevalmethod. It contains the operations to be executed. -
1: This parameter indicates the number of keys the Lua script will work with. In this context, it informs Redis that there is only one key being manipulated in the script. -
'counter': This parameter is the actual key that the Lua script will operate on. It corresponds toKEYS[1]in the Lua script since Lua uses 1-based indexing. -
5: This is the first argument to the Lua script (accessible within the Lua script asARGV[1]). In the script, this value is used to increment the current value of the keycounter.
Now, let's break down the Lua code used:
- The
KEYSvariable holds the keys the script will work with — here,KEYS[1]iscounter. Note that Lua uses 1-based indexing. - The
ARGVvariable holds the script's arguments — here,ARGV[1]is5.
The Lua script performs these operations:
- Retrieve the current value of the key
counter. - Increment the key's value by the script argument (
5) if it exists. - If the key doesn't exist, set its value to
5. - Utilize
redis.callto perform thesetoperation on Redis.
