如何在nodejs中编写池的获取 - 处理 - 释放?

时间:2015-05-21 02:53:04

标签: javascript node.js

我想在java中实现像AOP这样的常用功能。例如,我有一个redis池,acquire-processing-release就是这样的:

public class JedisInterceptor implements MethodInterceptor{

@Inject private Session<Jedis> session;

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    if(!session.isClosed()) return invocation.proceed();
    try {
        //acquire connection from pool
        session.start();
        return invocation.proceed();
    } catch (Throwable e) {
        throw e;
    } finally {
        if(!session.isClosed()) {
            //always release connection no matter there's exception or not.
            session.close();
        }
    }
}

我在nodejs中需要一个相同的功能,我指的是异步,但仍然令人沮丧。这是nodejs代码:

var pool = require('generic-pool');

var redis = require("redis");

var async = require('async');

//Redis pool
var redisPool = pool.Pool({
    name: 'redis',
    create: function(callback) {
        var connection = redis.createClient(6379, '127.0.0.1', {});
        callback(null, connection);
    },
    destroy: function(connection) {
        connection.quit();
    },
    max: 5,
    min: 2,
    idleTimeoutMillis: 30000,
    log: false
});

module.exports = {
    redis: function(fn) {
        //How to code here by using async ?
    }
} 

然后我可以在像bellowed这样的地方使用这个功能,而不用担心连接处理。

var value = Utils.redis(function(redis){
    return redis.get('something')
});

0 个答案:

没有答案
相关问题