sewenew / redis-plus-plus

Redis client written in C++
Apache License 2.0
1.64k stars 351 forks source link

[QUESTION] Issues with MovedError with RedisCluster pipelines #456

Closed marcbak closed 1 year ago

marcbak commented 1 year ago

Hi, I have a setup with 3 redis master node, I'm connecting to one of those and I'm trying to use a Pipeline to daisy chain two redis commands. This is my minimal working example

#include <regex>
#include <iostream>
#include <fmt/core.h>
#include <sw/redis++/redis++.h>

namespace {
    constexpr auto FIRST_PREFIX = "request_per_session";
    constexpr auto SECOND_PREFIX = "request_per_device";
}

unsigned get_minute() { return (time(nullptr) / 60) % 60; }

void make_redis_request(std::shared_ptr<sw::redis::RedisCluster>& redis, const std::string& prefix, const std::string& id)
{
    constexpr auto TTL = 59;
    const auto minute = get_minute();
    const auto key = fmt::format("{}:{:02}", prefix, minute);
    bool try_again = false;
    try {
        auto pipeline = redis->pipeline(prefix, false);
        auto result = pipeline.zincrby(key, 1, id).expire(key, TTL).exec();
        auto incrby_result = result.get<double>(0);
        std::cout << "incrby result" << incrby_result << std::endl;
        auto expire_result = result.get<bool>(1);
        std::cout << "expire result" <<  expire_result << std::endl;
    }
    catch (const std::exception &moved_error) {
        std::cout << moved_error.what() << std::endl;
    }

}

int main() {
    sw::redis::ConnectionPoolOptions pool_options;
    pool_options.size = 4;
    pool_options.wait_timeout = std::chrono::milliseconds(50);
    sw::redis::ConnectionOptions connection_options;
    connection_options.host = "10.10.10.43";
    auto redis = std::make_shared<sw::redis::RedisCluster>(connection_options, pool_options);
    make_redis_request(redis, FIRST_PREFIX, "100");
    make_redis_request(redis, SECOND_PREFIX, "200");

    make_redis_request(redis, FIRST_PREFIX, "100");
    make_redis_request(redis, SECOND_PREFIX, "200");

    return 0;
}

The result I get is:

839 10.10.10.41:6379
7511 10.10.10.42:6379
839 10.10.10.41:6379
7511 10.10.10.42:6379

I'm a bit lost on how to how to handle this error, I've tried the following:

But none of these seem to work. I've looked around the issues here, checked stackoverflow and can't seem to run into anyone that's having the same problem as I do. I'm no redis expert, so I might be missing something obvious, but I'm really out of ideas here.

Potential problems that I can think of:

Environment:

marcbak commented 1 year ago

Setting the hashtag to key rather than prefix seems to have fixed all my issues. I was looking in the wrong place :facepalm: