tedis2
Version:
redis client for node.js with typescript and async
98 lines (97 loc) • 2.98 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TedisPool = void 0;
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.timeout = options.timeout;
this.tls = options.tls;
}
release() {
this.connection_pool.forEach(conn => {
conn.close();
});
}
async getTedis() {
const conn = this.connection_pool.shift();
if ("undefined" !== typeof conn) {
return conn;
}
else if (this.act_conn < this.max_conn) {
return await 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) => {
this.act_conn++;
const conn = new tedis_1.Tedis({
host: this.host,
port: this.port,
password: this.password,
timeout: this.timeout,
tls: this.tls,
});
conn.on("connect", () => {
conn.on("error", err => {
console.log(err);
});
conn.on("close", (had_error) => {
this.closeConnection(conn);
});
conn.on("timeout", () => {
this.miniConnection(conn);
});
resolve(conn);
});
conn.on("error", err => {
this.act_conn--;
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();
}
}
}
exports.TedisPool = TedisPool;