int RedisModule_CreateCommand( RedisModuleCtx *ctx, const char *name, RedisModuleCmdFunc cmdfunc, const char *strflags, int firstkey, int lastkey, int keystep)
Parameters:
name - Command name (use dots for namespacing)
cmdfunc - Function pointer to command implementation
strflags - Space-separated command flags
firstkey - Position of first key argument (0 if none)
lastkey - Position of last key argument (0 if none)
/* COUNTER.INCR <key> [amount] - Increment a counter */int CounterIncr_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { if (argc < 2 || argc > 3) { return RedisModule_WrongArity(ctx); } // Enable automatic memory management RedisModule_AutoMemory(ctx); // Parse increment amount (default 1) long long incr = 1; if (argc == 3) { if (RedisModule_StringToLongLong(argv[2], &incr) != REDISMODULE_OK) { return RedisModule_ReplyWithError(ctx, "ERR invalid increment"); } } // Open key for writing RedisModuleKey *key = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE); int keytype = RedisModule_KeyType(key); // Check if key exists and is the right type if (keytype != REDISMODULE_KEYTYPE_EMPTY && keytype != REDISMODULE_KEYTYPE_STRING) { return RedisModule_ReplyWithError(ctx, REDISMODULE_ERRORMSG_WRONGTYPE); } // Get current value long long value = 0; if (keytype == REDISMODULE_KEYTYPE_STRING) { size_t len; char *str = RedisModule_StringDMA(key, &len, REDISMODULE_READ); if (str == NULL || sscanf(str, "%lld", &value) != 1) { return RedisModule_ReplyWithError(ctx, "ERR value is not an integer"); } } // Increment value value += incr; // Save new value RedisModuleString *newval = RedisModule_CreateStringFromLongLong(ctx, value); RedisModule_StringSet(key, newval); // Replicate command RedisModule_ReplicateVerbatim(ctx); return RedisModule_ReplyWithLongLong(ctx, value);}
Use RedisModule_AutoMemory(ctx) to automatically free allocations:
int MyCommand_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) { RedisModule_AutoMemory(ctx); // Auto-free on function return RedisModuleString *str = RedisModule_CreateString(ctx, "data", 4); // No need to free str - handled automatically return REDISMODULE_OK;}