跳转到主要内容

Twisted的通用连接池库

项目描述

Twisted的通用连接池库。

示例描述

假设我们有一个Web应用程序,它执行一些昂贵的计算,然后将它们缓存到一个memcached服务器中。在Twisted中实现这一点的简单方法是创建一个ClientCreator用于MemCacheProtocol,并且每当我们需要与服务器通信时,我们可以简单地使用它。

这对于查询量较低的情况有效,但假设我们现在开始大量地访问memcached - 每个Web请求中都有很多次,我们每秒都接收到很多。很快,连接开销就会成为一个问题。

而不是为每个查询创建新的连接,维护一个打开的连接池会更好,简单重用这些打开的连接;如果所有连接都在使用中,则排队任何查询。使用txconnpool,设置这可以相当简单。

示例实现

首先我们需要创建一些模板类,将MemCacheProtocol转换为PooledMemcachedProtocol,然后创建一个池

from twisted.protocols.memcache import MemCacheProtocol

from txconnpool.pool import PooledClientFactory, Pool

class PooledMemCacheProtocol(MemCacheProtocol):
    """
    A MemCacheProtocol that will notify a connectionPool that it is ready
    to accept requests.
    """
    factory = None

    def connectionMade(self):
        """
        Notify our factory that we're ready to accept connections.
        """
        MemCacheProtocol.connectionMade(self)

        self.factory.connectionPool.clientFree(self)

        if self.factory.deferred is not None:
            self.factory.deferred.callback(self)
            self.factory.deferred = None

class MemCacheClientFactory(PooledClientFactory):
    protocol = PooledMemCacheProtocol

class MemCachePool(Pool):
    clientFactory = MemCacheClientFactory

    def get(self, *args, **kwargs):
        return self.performRequest('get', *args, **kwargs)

    def set(self, *args, **kwargs):
        return self.performRequest('set', *args, **kwargs)

    def delete(self, *args, **kwargs):
        return self.performRequest('delete', *args, **kwargs)

    def add(self, *args, **kwargs):
        return self.performRequest('add', *args, **kwargs)

现在,创建完成后,我们可以继续使用它

from twisted.internet.address import IPv4Address

addr = IPv4Address('TCP', '127.0.0.1', 11211)
mc_pool = MemCachePool(addr, maxClients=20)

d = mc_pool.get('cached-data')

def gotCachedData(data):
    flags, value = data
    if value:
        print 'Yay, we got a cache hit'
    else:
        print 'Boo, it was a cache miss'

d.addCallback(gotCachedData)

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分发

txconnpool-0.1.1.tar.gz (7.1 kB 查看哈希值)

上传时间 源代码

由以下组织支持