How to call a Redis Function with StackExchange.Redis

Viewed 30

I wrote and register this Redis Function:

local function stincr(KEYS, ARGS)    
     local value = redis.pcall('INCR', KEYS[1])
     if value == 1 or value % 100 == 0 then
        redis.call('ZADD', KEYS[2],'GT', tostring(value), KEYS[1])
     end
     return value;
end
redis.register_function('stincr', stincr)

Redis Functions are introduced in Redis 7. How can I call it with StackExchange.Redis?

1 Answers

As of right now StackExchange.Redis doesn't have any higher-level API wrapping up the functions API, however, you can just use the ad-hoc command API pretty easily. I modified your script to add the shebang in the beginning called for by redis and added it to script.lua:

#!lua name=mylib
local function stincr(KEYS, ARGS)    
     local value = redis.pcall('INCR', KEYS[1])
     if value == 1 or value % 100 == 0 then
        redis.call('ZADD', KEYS[2],'GT', tostring(value), KEYS[1])
     end
     return value;
end
redis.register_function('stincr', stincr)

Then loading/calling the function was pretty straight forward:

var script = File.ReadAllText("script.lua");

var muxer = ConnectionMultiplexer.Connect("localhost");

var db = muxer.GetDatabase();

db.Execute("FUNCTION", "LOAD", script);
var res = db.Execute("FCALL", "stincr", 2, "myNum", "myzset");
Related