216 lines
5.9 KiB
C++
216 lines
5.9 KiB
C++
#include "redis_pool.hpp"
|
|
#include "errors.hpp"
|
|
|
|
#include <chrono>
|
|
#include <cstdlib>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
|
|
namespace {
|
|
|
|
constexpr timeval kConnectTimeout{2, 0};
|
|
constexpr timeval kCommandTimeout{2, 0};
|
|
constexpr auto kAcquireTimeout = std::chrono::seconds(3);
|
|
|
|
struct RedisUrl {
|
|
std::string host = "127.0.0.1";
|
|
int port = 6379;
|
|
std::string password;
|
|
int db = 0;
|
|
};
|
|
|
|
RedisUrl parse_redis_url(const std::string& url) {
|
|
RedisUrl out;
|
|
const std::string prefix = "redis://";
|
|
if (url.compare(0, prefix.size(), prefix) != 0) {
|
|
throw std::runtime_error("redis url must start with redis://");
|
|
}
|
|
std::string rest = url.substr(prefix.size());
|
|
|
|
const auto slash = rest.find('/');
|
|
if (slash != std::string::npos) {
|
|
const std::string db_str = rest.substr(slash + 1);
|
|
rest.resize(slash);
|
|
if (!db_str.empty()) {
|
|
out.db = std::atoi(db_str.c_str());
|
|
}
|
|
}
|
|
|
|
const auto at = rest.find('@');
|
|
std::string hostport = rest;
|
|
if (at != std::string::npos) {
|
|
const std::string creds = rest.substr(0, at);
|
|
hostport = rest.substr(at + 1);
|
|
const auto colon = creds.find(':');
|
|
if (colon != std::string::npos) {
|
|
out.password = creds.substr(colon + 1);
|
|
} else {
|
|
out.password = creds;
|
|
}
|
|
}
|
|
|
|
const auto colon = hostport.find(':');
|
|
if (colon == std::string::npos) {
|
|
out.host = hostport;
|
|
} else {
|
|
out.host = hostport.substr(0, colon);
|
|
out.port = std::atoi(hostport.substr(colon + 1).c_str());
|
|
}
|
|
|
|
return out;
|
|
}
|
|
|
|
redisContext* make_connection(const RedisUrl& u) {
|
|
redisContext* c = redisConnectWithTimeout(u.host.c_str(), u.port, kConnectTimeout);
|
|
if (c == nullptr) {
|
|
throw std::runtime_error("redisConnect: allocation failed");
|
|
}
|
|
if (c->err) {
|
|
const std::string err = c->errstr;
|
|
redisFree(c);
|
|
throw DependencyUnavailable("redisConnect failed: " + err);
|
|
}
|
|
if (redisSetTimeout(c, kCommandTimeout) != REDIS_OK) {
|
|
redisFree(c);
|
|
throw DependencyUnavailable("redisSetTimeout failed");
|
|
}
|
|
if (!u.password.empty()) {
|
|
redisReply* r = static_cast<redisReply*>(
|
|
redisCommand(c, "AUTH %s", u.password.c_str()));
|
|
if (r == nullptr) {
|
|
redisFree(c);
|
|
throw std::runtime_error("redis AUTH: no reply");
|
|
}
|
|
const bool ok = (r->type == REDIS_REPLY_STATUS);
|
|
freeReplyObject(r);
|
|
if (!ok) {
|
|
redisFree(c);
|
|
throw std::runtime_error("redis AUTH failed");
|
|
}
|
|
}
|
|
if (u.db != 0) {
|
|
redisReply* r = static_cast<redisReply*>(
|
|
redisCommand(c, "SELECT %d", u.db));
|
|
if (r == nullptr) {
|
|
redisFree(c);
|
|
throw std::runtime_error("redis SELECT: no reply");
|
|
}
|
|
const bool ok = (r->type == REDIS_REPLY_STATUS);
|
|
freeReplyObject(r);
|
|
if (!ok) {
|
|
redisFree(c);
|
|
throw std::runtime_error("redis SELECT failed");
|
|
}
|
|
}
|
|
return c;
|
|
}
|
|
|
|
}
|
|
|
|
RedisPool::RedisPool(std::string url, std::size_t n)
|
|
: url_(std::move(url)) {
|
|
if (n == 0) {
|
|
throw std::runtime_error("RedisPool: n must be > 0");
|
|
}
|
|
const RedisUrl parsed = parse_redis_url(url_);
|
|
all_.reserve(n);
|
|
idle_.reserve(n);
|
|
for (std::size_t i = 0; i < n; ++i) {
|
|
ConnPtr c(make_connection(parsed));
|
|
idle_.push_back(c.get());
|
|
all_.push_back(std::move(c));
|
|
}
|
|
}
|
|
|
|
RedisPool::~RedisPool() {
|
|
{
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
shutting_down_ = true;
|
|
}
|
|
cv_.notify_all();
|
|
}
|
|
|
|
RedisPool::Lease::Lease(RedisPool& pool)
|
|
: pool_(&pool), ctx_(pool.take()) {}
|
|
|
|
RedisPool::Lease::~Lease() {
|
|
if (pool_ != nullptr && ctx_ != nullptr) {
|
|
pool_->give_back(ctx_);
|
|
}
|
|
}
|
|
|
|
RedisPool::Lease::Lease(Lease&& other) noexcept
|
|
: pool_(other.pool_), ctx_(other.ctx_) {
|
|
other.pool_ = nullptr;
|
|
other.ctx_ = nullptr;
|
|
}
|
|
|
|
RedisPool::Lease RedisPool::acquire() {
|
|
return Lease(*this);
|
|
}
|
|
|
|
redisContext* RedisPool::take() {
|
|
std::unique_lock<std::mutex> lk(mu_);
|
|
if (!cv_.wait_for(lk, kAcquireTimeout,
|
|
[&]() { return shutting_down_ || !idle_.empty(); })) {
|
|
throw DependencyUnavailable("redis pool: acquire timeout");
|
|
}
|
|
if (shutting_down_) {
|
|
throw DependencyUnavailable("redis pool is shutting down");
|
|
}
|
|
redisContext* c = idle_.back();
|
|
idle_.pop_back();
|
|
lk.unlock();
|
|
|
|
bool alive = false;
|
|
if (!c->err) {
|
|
redisReply* r = static_cast<redisReply*>(redisCommand(c, "PING"));
|
|
if (r != nullptr && r->type == REDIS_REPLY_STATUS) {
|
|
alive = true;
|
|
}
|
|
if (r != nullptr) freeReplyObject(r);
|
|
}
|
|
if (alive) {
|
|
return c;
|
|
}
|
|
|
|
ConnPtr fresh;
|
|
try {
|
|
fresh.reset(make_connection(parse_redis_url(url_)));
|
|
} catch (const std::exception& e) {
|
|
// Слот возвращается в пул, иначе после нескольких неудач пул опустеет навсегда.
|
|
give_back(c);
|
|
throw DependencyUnavailable(std::string("redis reconnect failed: ") + e.what());
|
|
}
|
|
|
|
std::lock_guard<std::mutex> lk2(mu_);
|
|
for (auto& up : all_) {
|
|
if (up.get() == c) {
|
|
up = std::move(fresh);
|
|
return up.get();
|
|
}
|
|
}
|
|
throw std::logic_error("RedisPool: connection not owned by pool");
|
|
}
|
|
|
|
void RedisPool::give_back(redisContext* c) {
|
|
{
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
idle_.push_back(c);
|
|
}
|
|
cv_.notify_one();
|
|
}
|
|
|
|
bool RedisPool::ping() {
|
|
try {
|
|
auto lease = acquire();
|
|
redisContext* c = lease.ctx();
|
|
redisReply* r = static_cast<redisReply*>(redisCommand(c, "PING"));
|
|
if (r == nullptr) return false;
|
|
const bool ok = (r->type == REDIS_REPLY_STATUS);
|
|
freeReplyObject(r);
|
|
return ok;
|
|
} catch (...) {
|
|
return false;
|
|
}
|
|
} |