Let's see how it works.
-
Connect to the Redis server using the Redis command-line interface (redis-cli
).
redis-cli
-
Now, let's load a Lua script using SCRIPT LOAD
. We'll use the same script from the previous step that increments a counter by a specified amount.
SCRIPT LOAD "local current = redis.call('INCRBY', KEYS[1], ARGV[1]); return current"
This command will load the script into the Redis server's script cache and return the SHA1 hash of the script. You should see output similar to this:
"6b1e8dd2999cb08546e74339c0c9489f9f89a84b"
This is the SHA1 hash of the script. Make a note of this hash, as you'll need it in the next step. The exact hash value may differ.
-
Now, let's load the script that sets a key to a value, where both the key and the value are passed as arguments.
SCRIPT LOAD "redis.call('SET', KEYS[1], ARGV[1]); return ARGV[1]"
You should see output similar to this:
"a8b2b3648969459a8198262a9166e945e890987c"
Again, make a note of this hash.
-
Let's load the script that concatenates two strings passed as arguments and sets the result to a key.
SCRIPT LOAD "local result = ARGV[1] .. ARGV[2]; redis.call('SET', KEYS[1], result); return result"
You should see output similar to this:
"d2a800a974ca96849295220424f9a0664a495345"
Make a note of this hash as well.
-
You can verify that the scripts are loaded using the SCRIPT EXISTS
command. This command takes one or more SHA1 hashes as arguments and returns an array of 0s and 1s, where 1 indicates that the script with the corresponding hash is loaded and 0 indicates that it is not.
For example, to check if the first script we loaded is still loaded, use the following command, replacing the hash with the one you obtained in step 2:
SCRIPT EXISTS 6b1e8dd2999cb08546e74339c0c9489f9f89a84b
Output:
1) (integer) 1
This indicates that the script is loaded.
If you try to check for a script that is not loaded:
SCRIPT EXISTS 0000000000000000000000000000000000000000
Output:
1) (integer) 0
This indicates that the script is not loaded.
-
Exit the redis-cli
. This is important for the changes to be logged.
exit