nodejs之memcached连接池

来源:互联网 发布:成都程序员工资水平 编辑:程序博客网 时间:2024/06/07 01:31

nodejs之memcached连接池:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
 * memcached 连接池
 **/
varoptions = {
    //'host': ['localhost:11211'],
    'host':'localhost:11211',
    'connectionLimit':'2',
    'timeout': 50000
};
varpoolModule = require('generic-pool');
console.log("init pool for memcached start..");
varpool = poolModule.Pool({
    name : 'memcached',
    create : function(callback){
        varMemcached = require('memcached');
        memcached = newMemcached(options.host, {debug: true});
        memcached.on("failure",function(detail) {})
                 .on('connect',function(detail) {})
                 .on('reconnect',function(detail) {})
                 .on('reconnecting',function(detail) {})
                 .on('remove',function(detail) {})
                 .on('issue',function(detail) {});
        callback(null, memcached);
    },
    destory : function(client){
        if(client.connected){
            try{
                client.end();
            }
            catch(err){
                console.log('Failed to memcached connection: ' + err);
            }
        }
    },
    max : options.connectionLimit,
    idleTimeoutMillis : options.timeout,
    log : false
});
console.log("init pool for memcached end....");
 
exports.set = function(key, val, expire, callback){
    pool.acquire(function(err, client){
        if(err){
            callback(err);
            return;
        }
        if(!expire) expire = 172800;
        client.set(key, val, expire, function(err, data){
            pool.release(client);
            if(err){
                callback(err,null);
                return;
            }
            callback(err, data);
        });
    });
};
 
exports.get = function(key, callback){
    pool.acquire(function(err, client){
        if(err){
            callback(err);
            return;
        }
        client.get(key,function(err, data){
            pool.release(client);
            if(err){
                callback(err,null);
                return;
            }
            callback(err, data);
        });
    });
};
原创粉丝点击