This is not the same as stored procedures in RDBMS. These loaded scripts are not stored by redis server, they are just cached. so once server restarted, loaded scripts will be gone.
2 possible ways:
You provide the full text of the script for the first execution of the script (i.e. EVAL
for the first execution) then you can use EVALSHA
for all subsequent calls.
EVALSHA
returns special error NOSCRIPT: No Matching script, Please Use [EVAL]
in case this SHA digest is invalid so the client can always optimistically send EVALSHA
under the hood even when the client actually send EVAL
. if NOSCRIPT
returned, EVAL
will be used instead.
You can use SCRIPT EXISTS
and load the script using SCRIPT LOAD
in case it doesn't exist.
Check whether script exists:
SCRIPT EXISTS sha1 sha2 ... shaN
Load script:
SCRIPT LOAD script
Or code of the application (including Lua scripts) is managed on application side and you send script everytime you need to execute it if it is small text, in this case you do not need to configure or do anything in Redis side. This is very useful in the context of a distributed environment and with Redis cluster.
A third approach where you may want to change the behavior by adding custom startup scripts in linux where you start redis server and then load all of your scripts there however your app code still won't know anything about these SHA hashes but I don't like this approach with also difficulties in distributed environments.
More Info:
redis-cli SCRIPT LOAD "$(cat myscript.lua)"
right after starting redis (can specify that in my docker-compose as I'm using docker)? To have the script loaded every time after startup? The problem is, even if this works, is this bad practice? I have to be 100% sure I'm not going to ever encounter the script being unloaded accidentally. – Behalfredis-cli -x script load < myscript.lua
. The$(cat myscript.lua)
converts LFs to spaces unless you temporarily set IFS=" " in bash. – Gary