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.
Prerequisites
Section titled “Prerequisites”- Running Valkey server (standalone or cluster)
- GLIDE installed.
Working with Valkey Functions
Section titled “Working with Valkey Functions”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.
-
Define the lua script.
lua_code = """#!lua name=example_moduleserver.register_function('set_then_get', function(key, value)server.call('SET', key, value)return server.call('GET', key)end)""" -
Load the function to Valkey.
await client.function_load(lua_code, replace=True) -
Call the function.
await client.set("page:home:visits", "0")result = await client.fcall("set_then_get", keys=["page:home:visits"], args=["1"])print(result) # b'1'
Full Example
import asynciofrom glide import Script, GlideClient, GlideClientConfiguration, NodeAddress
async def main(): config = GlideClientConfiguration(addresses=[NodeAddress("localhost", 6379)]) client = await GlideClient.create(config)
# lua code that updates a key and returns its new value lua_code = """#!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 await client.function_load(lua_code, replace=True)
await client.set("page:home:visits", "0") # calling the previously loaded function result = await client.fcall("update_visits", keys=["page:home:visits"]) print(result) # b'1'
if __name__ == "__main__": asyncio.run(main())-
Define the lua script.
String luaCode = """#!lua name=example_moduleserver.register_function('set_then_get', function(key, value)server.call('SET', key, value)return server.call('GET', key)end)"""; -
Load the function to Valkey.
client.functionLoad(luaCode, true).get(); -
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(); } }}-
Define the lua script.
const luaCode = `#!lua name=example_moduleserver.register_function('set_then_get', function(key, value)server.call('SET', key, value)return server.call('GET', key)end)`; -
Load the function to Valkey.
await client.functionLoad(luaCode, {replace: true}); -
Call the function.
await client.set("page:home:visits", "0");const result = await client.fcall("set_then_get",["page:home:visits"], ["1"]);console.log(result); // 1
Full Example
import {GlideClient} from "@valkey/valkey-glide";
async function main() { const client = await GlideClient.createClient({ addresses: [{host: "localhost", port: 6379}] });
// lua code that updates a key and returns its new value const 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 await client.functionLoad(luaCode, {replace: true});
await client.set("page:home:visits", "0"); // calling the previously loaded function const result = await client.fcall("update_visits", ["page:home:visits"], []); console.log(result); // 1
client.close();}
main();-
Define the lua script.
luaCode := `#!lua name=example_moduleserver.register_function('set_then_get', function(key, value)server.call('SET', key, value)return server.call('GET', key)end)` -
Load the function to Valkey.
_, err := client.FunctionLoad(ctx, luaCode, true)if err != nil {// handle error} -
Call the function.
_, err = client.Set(ctx, "page:home:visits", "0")if err != nil {// handle error}result, err := client.FCallWithKeysAndArgs(ctx, "set_then_get",[]string{"page:home:visits"}, []string{"1"})if err != nil {// handle error}fmt.Println(result) // 1
Full Example
package main
import ( "context" "fmt" glide "github.com/valkey-io/valkey-glide/go/v2" "github.com/valkey-io/valkey-glide/go/v2/config")
func main() { ctx := context.Background() myConfig := config.NewClientConfiguration(). WithAddress(&config.NodeAddress{Host: "localhost", Port: 6379})
client, err := glide.NewClient(myConfig) if err != nil { panic(err) } defer client.Close()
// lua code that updates a key and returns its new value 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 _, err = client.FunctionLoad(ctx, luaCode, true) if err != nil { panic(err) }
_, err = client.Set(ctx, "page:home:visits", "0") if err != nil { panic(err) }
// calling the previously loaded function result, err := client.FCallWithKeysAndArgs(ctx, "update_visits", []string{"page:home:visits"}, []string{}) if err != nil { panic(err) } fmt.Println(result) // 1}Read-Only Functions
Section titled “Read-Only Functions”GLIDE clients implement FCALL_RO command to execute read-only functions.
result = await client.fcall_ro("get_value", keys=["mykey"])With Routing (Cluster Mode)
from glide.routes import AllNodes, AllPrimaries, RandomNode
# Route to all nodesresult = await client.fcall_ro_route("get_value", AllNodes())
# Route to all primary nodesresult = await client.fcall_ro_route("get_value", AllPrimaries())
# Route to a random noderesult = await client.fcall_ro_route("get_value", RandomNode())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 nodesClusterValue<Object> result = client.fcallReadOnly("get_value", ALL_NODES).get();
// Route to all primary nodesClusterValue<Object> result = client.fcallReadOnly("get_value", ALL_PRIMARIES).get();const result = await client.fcallReadonly("get_value", ["mykey"]);With Routing (Cluster Mode)
// Route to all nodesconst result = await client.fcallReadonlyWithRoute("get_value", [], { route: "allNodes" });
// Route to all primary nodesconst result = await client.fcallReadonlyWithRoute("get_value", [], { route: "allPrimaries" });
// Route to a random nodeconst result = await client.fcallReadonlyWithRoute("get_value", [], { route: "randomNode" });result, err := client.FCallReadOnly(ctx, "get_value")With Routing (Cluster Mode)
import "github.com/valkey-io/valkey-glide/go/v2/config"
// Route to all nodesroute := config.SimpleNodeRoute(config.AllNodes)result, err := client.FCallReadOnlyWithRoute(ctx, "get_value", route)
// Route to all primary nodesroute := config.SimpleNodeRoute(config.AllPrimaries)result, err := client.FCallReadOnlyWithRoute(ctx, "get_value", route)
// Route to a random noderoute := config.SimpleNodeRoute(config.RandomNode)result, err := client.FCallReadOnlyWithRoute(ctx, "get_value", route)What’s Next
Section titled “What’s Next”For more on Valkey Function, visit the Valkey documentations.