redis.conf详解之module

2021-11-15  本文已影响0人  小易哥学呀学

1、用法:

$yourPath/redis.conf 文件中添加以下配置

loadmodule $yourPath/my.so

2、module制作:

准备工作

1:需要文件$yourPath/redismodule.h ,下载地址:https://github.com/redis/redis/blob/unstable/src/redismodule.h
2:安装gcc, 使用gcc --version检查是否安装

开始制作

step1将下方内容写入文件$yourPath/my.c

#include "redismodule.h"
#include <stdlib.h>

int HelloworldRand_RedisCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
    RedisModule_ReplyWithLongLong(ctx,rand());
    return REDISMODULE_OK;
}

int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
    if (RedisModule_Init(ctx,"helloworld",1,REDISMODULE_APIVER_1)
        == REDISMODULE_ERR) return REDISMODULE_ERR;

    if (RedisModule_CreateCommand(ctx,"helloworld.rand",
        HelloworldRand_RedisCommand, "fast random",
        0, 0, 0) == REDISMODULE_ERR)
        return REDISMODULE_ERR;

    return REDISMODULE_OK;
}

step2
-c表示只编译(compile),而不连接。
-o用于说明输出(output)文件名。
-fPIC指Position Independent Code。共享库要求有此选项,以便实现动态连接(dynamic linking)。
-shared表示生成一个共享库。
依次执行下列2条命令

$ gcc -c -fPIC -o my.o my.c
$ gcc -shared -o my.so my.o

step3
$yourPath/redis.conf 文件中添加以下配置

loadmodule $yourPath/my.so

step4启动redis

$ /usr/bin/redis-server yourPath/redis.conf

step5 验证与使用

$ redis-cli
127.0.0.1:6379> module list
1) 1) "name"
   2) "helloworld" // 加载成功
   3) "ver"
   4) (integer) 1
127.0.0.1:6379>
127.0.0.1:6379> helloworld.rand
(integer) 1358584661
127.0.0.1:6379>

原生注释

################################## MODULES #####################################

# Load modules at startup. If the server is not able to load modules
# it will abort. It is possible to use multiple loadmodule directives.
#
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so

其他
官方模块 https://redis.io/modules
官方模块制作 https://redis.io/topics/modules-intro

上一篇 下一篇

猜你喜欢

热点阅读