Redis Command Creation
Introduction
Redis is a powerful, open-source, in-memory data structure store that can be used as a database, cache, message broker, and more. While Redis comes with a rich set of built-in commands, there are scenarios where you might need to extend its functionality with custom commands to better suit your specific application requirements.
In this guide, we'll explore how to create custom Redis commands through Redis modules. This powerful feature allows you to extend Redis with new functionality written in C, giving you the ability to implement operations that aren't available in the standard command set.
Understanding Redis Modules
Redis modules are dynamic libraries that can be loaded into Redis at startup or runtime, adding new commands and data types. This modular architecture enables developers to extend Redis's functionality without modifying the Redis core.
Prerequisites
Before diving into creating Redis commands, you'll need:
- Basic knowledge of C programming language
- Redis server installed (version 4.0 or later)
- Development tools (gcc, make, etc.)
- Understanding of Redis data structures and commands
Creating Your First Redis Module
Let's start by creating a simple "HELLO" command that returns a greeting message.
Step 1: Set up the project structure
Create a directory for your module:
mkdir redis-hello-module
cd redis-hello-module
Step 2: Create the module source file
Create a file named hello.c
with the following content:
#include "redismodule.h"
#include <string.h>
/* HELLO [name] - Return a greeting to the user */
int HelloCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
if (argc < 2) {
return RedisModule_WrongArity(ctx);
}
RedisModuleString *name = argv[1];
size_t len;
const char *nameStr = RedisModule_StringPtrLen(name, &len);
RedisModule_ReplyWithSimpleString(ctx, nameStr ?
RedisModule_StringPtrLen(name, &len) :
"world");
return REDISMODULE_OK;
}
/* Module initialization */
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
/* Register the module with Redis */
if (RedisModule_Init(ctx, "hello", 1, REDISMODULE_APIVER_1) == REDISMODULE_ERR) {
return REDISMODULE_ERR;
}
/* Register the HELLO command */
if (RedisModule_CreateCommand(ctx, "HELLO",
HelloCommand,
"readonly",
1, 1, 1) == REDISMODULE_ERR) {
return REDISMODULE_ERR;
}
return REDISMODULE_OK;
}