Skip to content

Load and Execute Functions

Valkey scripting allows you to execute Lua code directly on the Valkey server. This guide will go over executing custom Lua scripts with GLIDE.

  • Running Valkey server (standalone or cluster)
  • GLIDE installed.

Valkey Functions is an alternative for persistent server-side Lua code. The following example shows a simple example of loading and executing a Valkey Function using GLIDE.

  1. Define the lua script.

    String luaCode = """
    #!lua name=example_module
    server.register_function('set_then_get', function(keys, args)
    server.call('SET', keys[1], args[1])
    return server.call('GET', keys[1])
    end)
    """;
  2. Load the function to Valkey.

    client.functionLoad(luaCode, true).get();
  3. Call the function.

    client.set("page:home:visits", "0").get();
    Object result = client.fcall("set_then_get",
    new String[]{"page:home:visits"}, new String[]{"1"}).get();
    System.out.println(result); // 1
Full Example
import glide.api.GlideClient;
import glide.api.models.configuration.GlideClientConfiguration;
import glide.api.models.configuration.NodeAddress;
public class Example {
public static void main(String[] args) {
GlideClientConfiguration config = GlideClientConfiguration.builder()
.address(NodeAddress.builder()
.host("localhost")
.port(6379)
.build())
.build();
try (GlideClient client = GlideClient.createClient(config).get()) {
// lua code that updates a key and returns its new value
String luaCode = """
#!lua name=page_visits
server.register_function('update_visits', function(visits)
server.call('INCR', visits[1])
return server.call('GET', visits[1])
end)
""";
// loading the function to valkey
client.functionLoad(luaCode, true).get();
client.set("page:home:visits", "0").get();
// calling the previously loaded function
Object result = client.fcall("update_visits",
new String[]{"page:home:visits"}, new String[]{}).get();
System.out.println(result); // 1
} catch (Exception e) {
e.printStackTrace();
}
}
}

GLIDE clients implement FCALL_RO command to execute read-only functions.

Object result = client.fcallReadOnly("get_value", new String[]{"mykey"}).get();

With Routing (Cluster Mode)

import static glide.api.models.configuration.RequestRoutingConfiguration.SimpleMultiNodeRoute.ALL_NODES;
import static glide.api.models.configuration.RequestRoutingConfiguration.SimpleMultiNodeRoute.ALL_PRIMARIES;
// Route to all nodes
ClusterValue<Object> result = client.fcallReadOnly("get_value", ALL_NODES).get();
// Route to all primary nodes
ClusterValue<Object> result = client.fcallReadOnly("get_value", ALL_PRIMARIES).get();

For more on Valkey Function, visit the Valkey documentations.