Create a gist now

Instantly share code, notes, and snippets.

Creating a redis Module in 15 lines of code!

A quick guide to write a very very simple "ECHO" style module to redis and load it. It's not really useful of course, but the idea is to illustrate how little boilerplate it takes.

Step 1: open your favorite editor and write/paste the following code in a file called module.c

#include "redismodule.h"
/* ECHO <string> - Echo back a string sent from the client */
int EchoCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
  if (argc < 2) return RedisModule_WrongArity(ctx);
  return RedisModule_ReplyWithString(ctx, argv[1]);
}

/* Registering the module */
int RedisModule_OnLoad(RedisModuleCtx *ctx) {
  if (RedisModule_Init(ctx, "example", 1, REDISMODULE_APIVER_1) == REDISMODULE_ERR) {
    return REDISMODULE_ERR;
  }
  if (RedisModule_CreateCommand(ctx, "example.echo", EchoCommand, "readonly", 1,1,1) == REDISMODULE_ERR) {
    return REDISMODULE_ERR;
  }
}

Step 2: Download redismodule.h to the same directory. http://bit.ly/1WpJ7gP (https://raw.githubusercontent.com/antirez/redis/unstable/src/redismodule.h)

Step 3: Compile the module:

On Linux:

$ gcc -fPIC -std=gnu99 -c -o module.o module.c
$ ld -o module.so module.o -shared -Bsymbolic -lc

On OSX:

$ gcc -dynamic -fno-common -std=gnu99 -c -o module.o module.c
$ ld -o module.so module.o -bundle -undefined dynamic_lookup -lc

And you're done!

Step 4: Download the unstable version of redis and build it in the same directory, from: http://bit.ly/1Wq1Fyc or https://codeload.github.com/antirez/redis/zip/unstable

unzip redis-unstable.zip
cd redis-unstable
make -j 4
cd ..

Step 5: Load the module from the directory it was build int:

$ ./redis-unstable/src/redis-server --loadmodule ./module.so

(If you already have redis installed and running, you'll want to add --port 9999 or another free port.

Step 6: Try it out!

$ redis-cli EXAMPLE.ECHO "hello world"

The code is available at http://bit.ly/1WpIvrH

@marcosnils

@dvirsky still waiting your PR for the LUA interface in Jedis 😄

BTW: Redis modules are on the way in jedis. xetorthio/jedis#1278

@dvirsky
Owner
dvirsky commented May 12, 2016

@marcosnils I haven't forgotten, I was just super busy preparing the modules related stuff for RedisConf. I'll get back to normal work next week, and hope to get it done soon.

Re the PR you linked - the most important thing is simple generic command handling. I wanted to test my modules with Jedis but didn't have the time to start overriding classes. So good to see that it's there. LoadModule via the protocol might not be part of the final API, or it might be turned off by default, as it's a potential security risk. Reloading modules will probably be.

@itamarhaber

@dvirsky shouldn't it be if (argc != 2)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment