gcl
Version:
码农村nodejs类库,完成解决回调陷阱,配置框架,IOC框架,统一多DB访问框架,可扩展日志框架和io/db/net/thread/pool 克隆表达式,加解密算法等等一系列基础类库和算法的实现
123 lines • 3.77 kB
JavaScript
import V from '../common/tool';
/**
* 仅限于池方式调用的方法
* @author(baibing)
* @param('size','')
* @param(func:创建对象的方法)
* @param(waitTime,过期时间)
*/
export const Pool = class {
constructor(size = 10, func, waitTime = 10) {
const that = this;
const { _, __ } = pri(that, {
size,
func,
waitTime,
data: [], //总数
have: [], //有可用资源
wait: [], //等待调用的请求
use: {}, //使用中的
KEY: Symbol('_____poolid'),
addUse: (v) => {
if (v) {
if (!V.isValid(v[__.KEY])) {
v[__.KEY] = V.random();
}
__.use[v[__.KEY]] = v;
}
},
delUse: (v) => {
if (v && V.isValid(v[__.KEY])) {
delete __.use[v[__.KEY]];
}
}
});
__.clear = new Clearer(_, __);
__.clear.start();
}
getValue() {
const { _, __ } = pri(this);
return V.callback(call => {
let v = __.have.pop();
if (v) {
v = v.value;
__.addUse(v);
call(null, v);
} else if (__.data.length < __.size) {
V.callback2(__.func, __).then(v => {
__.addUse(v);
__.data.push(v);
call(null, v);
});
} else {
__.wait.push({ endDate: new Date().add('s', __.waitTime), value: call, dispose: call });
}
});
}
setValue(v) {
const { _, __ } = pri(this);
if (V.isValid(v) && V.isValid(v[__.KEY])) {
if (__.wait.length > 0) { //仅针对getValue异步操作有效
__.wait.shift().value(null, v);
} else {
__.delUse(v);
__.have.push({
endDate: new Date().add('s', __.waitTime),
value: v,
dispose: function() {
if (v.dispose) V.tryC(v.dispose);
}
});
}
}
}
dispose() {
const { _, __ } = pri(this);
__.clear.stop();
for (let i in __.data) V.tryC(() => { if (__.data[i].dispose) __.data[i].dispose() });
for (let i in __.wait) V.tryC(() => { if (__.wait[i].dispose) __.wait[i].dispose() });
__.data = null;
__.have = null;
__.use = null;
}
};
export default { Pool };
const pri = V.pris();
class Clearer {
constructor(obj, objpri) {
const { _, __ } = pri(this, { obj: obj, pri: objpri });
this.tid = null;
}
check(datas) {
let endDate = datas.length > 0 ? datas[0].endDate : null;
if (V.isValid(endDate) && new Date().diff('ms', endDate) > 0) {
return false;
} else {
while (datas.length > 0) {
let val = datas.shift();
if (V.isValid(val.endDate) && new Date().diff('ms', val.endDate) <= 0) {
if (val.dispose) {
V.tryC(val.dispose);
}
} else return true;
val = null;
}
return true;
}
}
start() {
const { _, __ } = pri(this);
_.tid = global.setTimeout(() => {
let ret = _.check(__.pri.have);
_.check(__.pri.wait);
_.start();
},
500);
}
stop() {
const _ = this;
if (_.tid)
global.clearTimeout(_.tid);
_.tid = null;
}
};