UNPKG

redis-typescript

Version:

redis client for node.js with typescript and async

111 lines 3.87 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const tedis_1 = require("./tedis"); class TedisPool { constructor(options = {}) { this.connection_pool = []; this.cushion_list = []; this.min_conn = options.min_conn || 1; this.max_conn = options.max_conn || 10; this.act_conn = 0; this.host = options.host || "127.0.0.1"; this.port = options.port || 6379; this.password = options.password; this.init(); } release() { this.connection_pool.forEach((conn) => { conn.close(); }); } getTedis() { return __awaiter(this, void 0, void 0, function* () { const conn = this.connection_pool.shift(); if ("undefined" !== typeof conn) { return conn; } else if (this.act_conn < this.max_conn) { return yield this.newConnection(); } else { return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.cushion_list.shift(); reject("timeout, the connection pool is full"); }, 1000 * 20); this.cushion_list.push((res) => { clearTimeout(timer); this.cushion_list.shift(); resolve(res); }); }); } }); } putTedis(conn) { const callback = this.cushion_list.shift(); if ("undefined" !== typeof callback) { callback(conn); } else { this.connection_pool.push(conn); } } newConnection() { return new Promise((resolve, reject) => { if (this.connection_pool.length >= this.max_conn) { reject("The connection pool is full"); } const conn = new tedis_1.Tedis({ host: this.host, port: this.port, password: this.password, }); conn.on("connect", () => { conn.on("error", (err) => { console.log(err); }); conn.on("close", (had_error) => { this.closeConnection(conn); }); conn.on("timeout", () => { this.miniConnection(conn); }); this.act_conn++; resolve(conn); }); conn.on("error", (err) => { reject(err); }); }); } closeConnection(conn) { const index = this.connection_pool.findIndex((item) => { return item.id === conn.id; }); if (-1 !== index) { this.connection_pool.splice(index, 1); } this.act_conn--; } miniConnection(conn) { if (this.min_conn < this.act_conn) { conn.close(); } } init() { return __awaiter(this, void 0, void 0, function* () { this.putTedis(yield this.newConnection()); }); } } exports.TedisPool = TedisPool; //# sourceMappingURL=pool.js.map