0
0
Redisquery~5 mins

EVALSHA for cached scripts in Redis

Choose your learning style9 modes available
Introduction
EVALSHA lets you run a saved script in Redis quickly by using its unique ID instead of sending the whole script every time.
You want to run the same Lua script many times without sending it again.
You want faster script execution by avoiding repeated script parsing.
You want to reduce network traffic by sending only the script's ID.
You want to ensure the script is already loaded before running it.
You want to handle errors if the script is missing from Redis.
Syntax
Redis
EVALSHA <sha1> <numkeys> [key1 key2 ...] [arg1 arg2 ...]
sha1 is the unique ID of the cached script.
numkeys tells Redis how many keys you pass next.
Examples
Runs the cached script with SHA1 hash 'a3f5c9...' using 2 keys and 2 arguments.
Redis
EVALSHA a3f5c9e7d8b1c2e3f4a5b6c7d8e9f0a1b2c3d4e5 2 key1 key2 arg1 arg2
Runs a cached script with no keys and no arguments.
Redis
EVALSHA 5d41402abc4b2a76b9719d911017c592 0
Sample Program
First, load a simple script that returns the first key and first argument. Then run it using EVALSHA with the returned SHA1 hash.
Redis
SCRIPT LOAD "return {KEYS[1],ARGV[1]}"
EVALSHA <sha1> 1 mykey myarg
OutputSuccess
Important Notes
If the script is not cached, EVALSHA returns an error.
Use SCRIPT LOAD to get the SHA1 hash before calling EVALSHA.
EVALSHA is faster than EVAL because it skips script parsing.
Summary
EVALSHA runs a cached Lua script in Redis using its SHA1 hash.
It needs the number of keys and the keys and arguments to pass.
It is faster and saves bandwidth compared to sending the full script.