实现一个连接池

在程序中大部分对象都不需要重复利用,每次用完直接丢弃就可以了,但有一种对象不能这样做---TCP connection(socket),socket如果每次用完直接关闭会导致几个问题:
1.netstat 看TIME_WAIT或CLOSE_WAIT非常高。
2.每次重新建立连接需要消耗资源。

通过实现连接池能比较好的解决这个问题,redis,mongo客户端都实现了连接池,通过apache-common提供的object pool也能实现一个比较好的连接池,下面是模仿redis-py实现的一段连接池。


[img]http://dl.iteye.com/upload/attachment/0073/4318/1c4d1ed4-f0b1-33a3-afde-09d0b187a187.png[/img]


import threading
from time import sleep
import sys

class Connection(object):
def __init__(self):
self.conn = "conn"

class ConnectionPool(object):
def __init__(self):
self.max_connections = 10
self._created_connections = 0
self._available_connections = []
self._in_use_connections = set()

def get_connection(self):
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
return connection

def make_connection(self):

if self._created_connections >= self.max_connections:
raise Error("Too many connections")
self._created_connections += 1
return Connection()

def release(self, connection):

self._in_use_connections.remove(connection)
self._available_connections.append(connection)

class TestThread(threading.Thread):
def __init__(self,testobj):
threading.Thread.__init__(self)
self.pool = testobj

def run(self):
while True:
connect = self.pool.get_connection()
sleep(1)
self.pool.release(connect)
#print str(self.pool._created_connections)+":"+str(len(self.pool._in_use_connections))

test = ConnectionPool()

for i in xrange(8):
t = TestThread(test)
t.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值