標籤:
花了二天時間才測試成功 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;};
nodejs之memcache串連池應用方法