Skip to content

Instantly share code, notes, and snippets.

@irr
Forked from dvirsky/module.md
Created May 11, 2016 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irr/9007096ed08f41b094ae5f4dde904817 to your computer and use it in GitHub Desktop.
Save irr/9007096ed08f41b094ae5f4dde904817 to your computer and use it in GitHub Desktop.

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!

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

Step 3: Compile the module:

$ gcc -fPIC -std=gnu99 -c -o module.o module.c
$ ld -o module.so module.o -shared -Bsymbolic -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.

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

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