Script and ScriptRO classes allow you to execute Lua scripts efficiently by using Redis’s EVALSHA command, which caches scripts on the server for faster execution.
Overview
Scripts provide an optimized way to execute Lua code in Redis:- First execution attempts
EVALSHAwith the script’s SHA-1 hash - If the script isn’t cached, falls back to
EVALto load and execute it - Subsequent executions use the cached version via
EVALSHA
Creating Scripts
Script (Read-Write)
Create a script that can modify data:ScriptRO (Read-Only)
Create a read-only script that usesEVAL_RO and EVALSHA_RO:
The Lua script to execute
Script configuration options
A Script or ScriptRO instance based on the readonly option
Script Class
Properties
script
The Lua script source code.The Lua script source code
sha1
The SHA-1 hash of the script.The SHA-1 hash of the script (may be empty if not yet initialized)
Methods
eval()
Execute the script using theEVAL command (sends full script to Redis).
Array of Redis keys that the script will access
Array of additional arguments to pass to the script
The script execution result
evalsha()
Execute the script using theEVALSHA command (uses cached SHA-1 hash).
Array of Redis keys that the script will access
Array of additional arguments to pass to the script
The script execution result
exec()
Optimistically execute the script with automatic fallback.- First attempts
EVALSHA(fast, uses cached script) - If script not cached (NOSCRIPT error), falls back to
EVAL - Subsequent calls use the cached version
Array of Redis keys that the script will access. In Lua, access via
KEYS[1], KEYS[2], etc.Array of additional arguments. In Lua, access via
ARGV[1], ARGV[2], etc.The script execution result
ScriptRO Class
TheScriptRO class is identical to Script but uses read-only commands (EVAL_RO and EVALSHA_RO). This is useful for scripts that only read data and can be executed on read replicas.
Methods
evalRo()
Execute the script usingEVAL_RO.
Array of Redis keys to read
Array of additional arguments
The script execution result
evalshaRo()
Execute the script usingEVALSHA_RO.
Array of Redis keys to read
Array of additional arguments
The script execution result
exec()
Execute with automatic fallback (triesEVALSHA_RO, falls back to EVAL_RO).
Array of Redis keys to read
Array of additional arguments
The script execution result