【问题标题】:How to use Pub/sub with hiredis in C++?如何在 C++ 中将 Pub/sub 与hiredis 一起使用?
【发布时间】:2019-07-26 14:32:47
【问题描述】:

我正在尝试通过 c++ 使用hiredis 客户端测试redis 的这个发布/订阅功能。

我可以看到订阅某个频道似乎很容易通过 redisCommand Api 完成。

但是我想知道当有人发布到特定服务器时回复是如何返回的。

谢谢

【问题讨论】:

    标签: redis


    【解决方案1】:

    https://github.com/redis/hiredis/issues/55 aluiken 于 2012 年 3 月 2 日发表评论

    void onMessage(redisAsyncContext *c, void *reply, void *privdata) {
        redisReply *r = reply;
        if (reply == NULL) return;
    
        if (r->type == REDIS_REPLY_ARRAY) {
            for (int j = 0; j < r->elements; j++) {
                printf("%u) %s\n", j, r->element[j]->str);
            }
        }
    }
    
    int main (int argc, char **argv) {
        signal(SIGPIPE, SIG_IGN);
        struct event_base *base = event_base_new();
    
        redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
        if (c->err) {
            printf("error: %s\n", c->errstr);
            return 1;
        }
    
        redisLibeventAttach(c, base);
        redisAsyncCommand(c, onMessage, NULL, "SUBSCRIBE testtopic");
        event_base_dispatch(base);
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      这是一个较晚的答案,但您可以尝试redis-plus-plus,它基于hiredis,并用C++ 11 编写。

      免责声明:我是这个库的作者。如果您对此客户有任何问题,请随时let me know。如果你喜欢,也欢迎star it :)

      示例代码:

      Redis redis("tcp://127.0.0.1:6379");
      
      // Create a Subscriber.
      auto sub = redis.subscriber();
      
      // Set callback functions.
      sub.on_message([](std::string channel, std::string msg) {
          // Process message of MESSAGE type.
      });
      
      sub.on_pmessage([](std::string pattern, std::string channel, std::string msg) {
          // Process message of PMESSAGE type.
      });
      
      sub.on_meta([](Subscriber::MsgType type, OptionalString channel, long long num) {
          // Process message of META type.
      });
      
      // Subscribe to channels and patterns.
      sub.subscribe("channel1");
      sub.subscribe({"channel2", "channel3"});
      
      sub.psubscribe("pattern1*");
      
      // Consume messages in a loop.
      while (true) {
          try {
              sub.consume();
          } catch (...) {
              // Handle exceptions.
          }
      }
      

      查看doc了解详情。

      【讨论】:

        【解决方案3】:

        观察者模式是我们在 Redis 的 pub/sub 特性中看到的。

        所有订阅者都是观察者,主题是发布者正在修改的频道。

        当发布者修改频道时,即执行 redis-cli 之类的命令时,发布 foo 值 此更改由 Redis 服务器传达给所有观察者(即订阅者)

        所以 Redis 服务器有一个特定频道的所有观察者的列表。

        【讨论】:

          猜你喜欢
          • 2014-10-01
          • 1970-01-01
          • 2021-11-19
          • 1970-01-01
          • 1970-01-01
          • 2019-10-29
          • 1970-01-01
          • 2015-03-01
          • 1970-01-01
          相关资源
          最近更新 更多