Script loading and caching helps Redis run Lua scripts faster by saving them once and reusing them without sending the full script every time.
0
0
Script loading and caching in Redis
Introduction
You want to run the same Lua script multiple times in Redis without sending the whole script each time.
You want to improve performance by avoiding repeated script parsing.
You want to ensure a script is loaded before running it to avoid errors.
You want to share a script across multiple Redis clients efficiently.
You want to check if a script is already cached in Redis before loading it.
Syntax
Redis
SCRIPT LOAD <script> EVALSHA <sha1> <numkeys> [key ...] [arg ...] SCRIPT EXISTS <sha1> SCRIPT FLUSH
SCRIPT LOAD loads a Lua script and returns its SHA1 hash.
EVALSHA runs a cached script by its SHA1 hash, faster than EVAL.
Examples
Loads a Lua script that sets a key to a value and returns the script's SHA1 hash.
Redis
SCRIPT LOAD "return redis.call('set', KEYS[1], ARGV[1])"Runs the cached script identified by
<sha1> with one key and one argument.Redis
EVALSHA <sha1> 1 mykey myvalueChecks if the script with the given SHA1 hash is already cached in Redis.
Redis
SCRIPT EXISTS <sha1>
Removes all cached scripts from Redis.
Redis
SCRIPT FLUSH
Sample Program
This example loads a Lua script that sets a key to a value, runs it using its SHA1 hash, and then retrieves the value to confirm it was set.
Redis
127.0.0.1:6379> SCRIPT LOAD "return redis.call('set', KEYS[1], ARGV[1])" "e0e1f3c3a7f9b8d9c6a1b2c3d4e5f67890123456" 127.0.0.1:6379> EVALSHA e0e1f3c3a7f9b8d9c6a1b2c3d4e5f67890123456 1 mykey myvalue OK 127.0.0.1:6379> GET mykey "myvalue"
OutputSuccess
Important Notes
Always use EVALSHA after loading a script to save bandwidth and improve speed.
If you try to run EVALSHA with a SHA1 that Redis does not know, it will return an error.
You can use SCRIPT EXISTS to check if a script is cached before running it.
Summary
Script loading and caching lets Redis store Lua scripts by their SHA1 hash.
Use SCRIPT LOAD to load scripts and get their SHA1 hash.
Use EVALSHA to run cached scripts quickly without sending the full script again.