花了二天时间才测试成功 NODEJS技术太新了点 中英文的资料都少 所以记录下正确的nodejs之memcache连接池应用方法方便后来人
按理说memcached应该自带有连接池 但是不知道为什么总是不正确 外面再套一个暂时正常了 或许以后会有更方便的方法 先用着 欢迎指正
module.exports = MemCache78;
var EventEmitter = require(‘events‘).EventEmitter;
var Util = require(‘util‘);
Util.inherits(MemCache78, EventEmitter);
var Q = require(‘q‘);
var MemCache = require(‘memcached‘);
var poolModule = require(‘generic-pool‘);
function MemCache78( port,host ,max) {
EventEmitter.call(this);
this.host = host;
this.port = port;
this.max=max||10;
this.client = poolModule.Pool({
name : ‘mem‘,
create : function(callback) {
if(self.port===0){
callback(null, null);
return;
}
var client = new MemCache(host+‘:‘+port, {poolSize:2,reconnect:1000,retry:1000});
callback(null, client);
},
destroy : function(client) {
},
max : this.max,
idleTimeoutMillis : 30000,
priorityRange : 3,log:false
});
return this;
}{
MemCache78.prototype.get = function (key) {
var def = Q.defer();
var self = this;
if (this.port === 0) {
console.log("memcache.port is 0");
def.resolve(null);
return def.promise;
}
//var client = new MemCache(self.host+‘:‘+self.port, {poolSize:2});
this.client.acquire(function (err, client) {
client.get(key, function (err, reply) {
self.client.release(client);
if(key=="keynotexists4"){
console.log("keynotexists4"+reply);
console.log(err);
}
if (err) {
def.reject(new Error(err));
console.error(‘memcache GetData Error: ‘ + err + key);
return;
}
//qq云没有返回undef
if (reply == undefined)reply = null;
//unde 和null都可以用!reply判断
def.resolve(reply);
});
});
return def.promise;
};