49 lines
1.2 KiB
C++
49 lines
1.2 KiB
C++
#pragma once
|
|
|
|
#include <string>
|
|
#include <unordered_map>
|
|
#include <queue>
|
|
#include <mutex>
|
|
#include <chrono>
|
|
|
|
#ifdef _WIN32
|
|
#include <winsock2.h>
|
|
typedef SOCKET socket_t;
|
|
#else
|
|
#include <sys/socket.h>
|
|
typedef int socket_t;
|
|
#endif
|
|
|
|
class ConnectionPool {
|
|
private:
|
|
struct PooledConnection {
|
|
socket_t socket;
|
|
std::chrono::steady_clock::time_point last_used;
|
|
bool is_ssl;
|
|
};
|
|
|
|
std::unordered_map<std::string, std::queue<PooledConnection>> pool_;
|
|
mutable std::mutex pool_mutex_;
|
|
static constexpr int MAX_CONNECTIONS_PER_HOST = 4;
|
|
static constexpr int CONNECTION_TIMEOUT_SECONDS = 30;
|
|
|
|
public:
|
|
ConnectionPool() = default;
|
|
~ConnectionPool();
|
|
|
|
socket_t acquire_connection(const std::string& host, int port, bool is_ssl = false);
|
|
|
|
// returns connection to pool for reuse
|
|
void release_connection(const std::string& host, int port, socket_t socket, bool is_ssl = false);
|
|
|
|
void cleanup_expired();
|
|
|
|
size_t get_pool_size() const;
|
|
|
|
private:
|
|
std::string make_key(const std::string& host, int port, bool is_ssl) const;
|
|
bool is_socket_alive(socket_t socket) const;
|
|
};
|
|
|
|
extern ConnectionPool g_connection_pool;
|