twisted的通用连接池库
txconnpool的Python项目详细描述
twisted的通用连接池库。
示例说明
假设我们有一个web应用程序,它执行一些昂贵的 计算,然后将它们缓存在memcached服务器中。简单的方法 在twisted中实现这一点是为MemCacheProtocol创建一个ClientCreator 当我们需要与服务器通信时,我们可以简单地使用它。
这适用于少量的查询,但是假设现在我们开始 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)