【问题标题】:Sending data to Redis in JSON format using hiredis使用 hiredis 以 JSON 格式向 Redis 发送数据
【发布时间】:2023-01-19 21:29:35
【问题描述】:

我对 Redis 完全陌生。我有一个在嵌入式 Linux 设备上运行的 C 应用程序,它应该连接到本地公开的 Redis。我正在使用 Hiredis。

我可以使用 redisConnect() 成功连接到 Redis。

现在我需要以 attribute:value JSON 格式将数据点写入 Redis,例如如下所示:

{
  "value" : 1000.1,
  "unit"  : "mA",
  "name"  : "Current"
}

我一直在查看示例代码,但看不到任何能准确显示我想要实现的目标的内容。

如下使用 redisCommand() 可以吗? :

redisCommand(redisContext,"value %f unit %s name %s", 1000.1, "mA", "Current");

【问题讨论】:

  • 您是否检查过 Redis 的 RedisJSON 模块?
  • @GuyKorland 是的,我做到了,但对于我想要实现的目标来说似乎过于复杂。

标签: c json linux redis hiredis


【解决方案1】:

这是对我有用的:

#include <stdio.h>
#include <stdlib.h>

#include <hiredis.h>

int main(void) {
    redisContext *redis_ctx = NULL;
    redisReply *reply = NULL;
    struct timeval redis_timeout = { 1, 500000 }; // 1.5 seconds
    redis_ctx = redisConnectWithTimeout("127.0.0.1", 6379, redis_timeout);
    if (redis_ctx == NULL || redis_ctx->err) {
        if (redis_ctx) {
            printf("Redis Connection error: %s
", redis_ctx->errstr);
            redisFree(redis_ctx);
        } else {
            printf("Connection error: can't allocate redis context
");
        }
    }
    if (redis_ctx) {
        reply = redisCommand(redis_ctx, "PUBLISH test_channel {"attrb1":%d,"attrb2":%d,"attrb3":%s}", 1, 2, "11");
        printf("EXTRA EXTRA: %s", reply->str);
        freeReplyObject(reply);
        redisFree(redis_ctx);
    }

    return EXIT_SUCCESS;
}

请注意,传递给 redisCommand 的字符串的 JSON 部分在字段和值之间没有任何空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2022-09-26
    相关资源
    最近更新 更多