How does Redis execute Lua scripts?
There are two ways to execute Lua scripts in Redis: using the eval command and using the evalsha command.
- Evaluate a script with a specified number of keys and arguments using the EVAL command.
- script: Lua script
- number of keys: the amount of keys used in the script
- key [key …]: Keys used in the script
- script parameters
- For example, running a simple Lua script to add the values of two keys and return the result.
- Evaluate the sum of the values stored in keys ‘key1’ and ‘key2’ converted to numbers using Redis.
- EVALSHA Command:
EVALSHA sha1 numkeys key [key …] arg [arg …] - The SHA1 hash value of the Lua script already stored in Redis.
- Number of keys: quantity of keys used by the script.
- key [key …]: keys used by the script
- Script arguments: Arguments for the script
- Using the evalsha command to execute Lua scripts can improve performance because Redis will cache the scripts that have already been loaded.
- Firstly, load the Lua script into Redis.
- Load the script that sums up the values of two keys after converting them to numbers.
- Next, run the Lua script that has been loaded.
- Execute the SHA1 digest of the given script, passing in 2 keys, key1 and key2.
Please note:
- When using the eval or evalsha commands to execute Lua scripts, you can use the redis.call function to call Redis commands, and you can also use the redis.pcall function to call Redis commands with error handling.
- KEYS and ARGV are global variables in Lua scripts that can be used to access the keys and arguments passed to the script.