Lua scripting
Lua scripts run atomically inside Redis. A script can return any type, so the results are converted
into plain values (Long, String or ByteArray, List, Map, Boolean, Double or null).
The ...String variants return bulk strings as String, the ...Bytes variants as ByteArray.
val result = connPool.evalString(
"return redis.call('INCRBY', KEYS[1], ARGV[1])",
keys = listOf("counter"),
args = listOf("5"),
) // 5L
Re-using scripts
RedisScript computes the SHA1 of the script locally. On a connection (or connection pool) it runs the script
via EVALSHA and loads it with SCRIPT LOAD only if Redis does not know it yet:
val incrBy = RedisScript("return redis.call('INCRBY', KEYS[1], ARGV[1])")
connPool.evalString(incrBy, listOf("counter"), listOf("5"))
Inside a pipeline {} or transactionPipeline {} use evalShaString(script.sha1, ...) after loading the
script with scriptLoad(...), as the result of a pipeline is only known after all commands were sent.
Errors
Errors raised by a script (or by a command called with redis.call) are thrown as RedisErrorReplyException,
which holds the error reply in reply. The connection stays usable.
Read-only scripts
Pass readOnly = true to use EVAL_RO/EVALSHA_RO (Redis 7+), which reject write commands and can run on replicas.