Skip to content

Scripting

Valkey versions 2.6 and higher provide support for running Lua scripts through the eval and evalsha commands. Spring Data Valkey provides a high-level abstraction for running scripts that handles serialization and automatically uses the Valkey script cache.

Scripts can be run by calling the execute methods of ValkeyTemplate and ReactiveValkeyTemplate. Both use a configurable io.valkey.springframework.data.core.script.ScriptExecutor (or io.valkey.springframework.data.core.script.ReactiveScriptExecutor) to run the provided script. By default, the io.valkey.springframework.data.core.script.ScriptExecutor (or io.valkey.springframework.data.core.script.ReactiveScriptExecutor) takes care of serializing the provided keys and arguments and deserializing the script result. This is done through the key and value serializers of the template. There is an additional overload that lets you pass custom serializers for the script arguments and the result.

The default io.valkey.springframework.data.core.script.ScriptExecutor optimizes performance by retrieving the SHA1 of the script and attempting first to run evalsha, falling back to eval if the script is not yet present in the Valkey script cache.

The following example runs a common “check-and-set” scenario by using a Lua script. This is an ideal use case for a Valkey script, as it requires that running a set of commands atomically, and the behavior of one command is influenced by the result of another.

@Bean
public ValkeyScript<Boolean> script() {
ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("META-INF/scripts/checkandset.lua"));
return ValkeyScript.of(scriptSource, Boolean.class);
}
public class Example {
@Autowired
ValkeyOperations<String, String> valkeyOperations;
@Autowired
ValkeyScript<Boolean> script;
public boolean checkAndSet(String expectedValue, String newValue) {
return valkeyOperations.execute(script, List.of("key"), expectedValue, newValue);
}
}
-- checkandset.lua
local current = valkey.call('GET', KEYS[1])
if current == ARGV[1]
then valkey.call('SET', KEYS[1], ARGV[2])
return true
end
return false

The preceding code configures a io.valkey.springframework.data.core.script.ValkeyScript pointing to a file called checkandset.lua, which is expected to return a boolean value. The script resultType should be one of Long, Boolean, List, or a deserialized value type. It can also be null if the script returns a throw-away status (specifically, OK).

The checkAndSet method above then runs the scripts. Scripts can be run within a io.valkey.springframework.data.core.SessionCallback as part of a transaction or pipeline. See “Valkey Transactions” and “Pipelining” for more information.

The scripting support provided by Spring Data Valkey also lets you schedule Valkey scripts for periodic running by using the Spring Task and Scheduler abstractions. See the Spring Framework documentation for more details.