Created
June 21, 2012 11:43
-
-
Save notsobad/2965283 to your computer and use it in GitHub Desktop.
Mongo wraper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#encoding: utf-8 | |
""" | |
By notsobad | |
""" | |
import sys | |
import time | |
import socket | |
import pymongo | |
from pymongo.errors import AutoReconnect | |
class CMongo(): | |
""" MongoDB 接口 """ | |
def __init__(self, delay=1, max_try=60): | |
self._conn = {} | |
self.delay = delay | |
self.max_try = max_try | |
def __getitem__(self, name): | |
return self.connect(*name) | |
def connect(self, host, port, **kw): | |
key = "%(host)s:%(port)s" % locals() | |
if key in self._conn: | |
try: | |
self._conn[key].is_locked | |
return self._conn[key] | |
except socket.error, e: | |
print >>sys.stderr, 'Lost connection: %s, retry' % str(e) | |
i = 0 | |
while True: | |
try: | |
self._conn[key] = pymongo.Connection(host, int(port), **kw) | |
return self._conn[key] | |
except AutoReconnect, e: | |
print >>sys.stderr, 'pymongo.Connection: %s, retry' % str(e) | |
time.sleep(self.delay) | |
i += 1 | |
if i >= self.max_try: | |
raise AutoReconnect('Mongo serverver may died') | |
def __del__(self): | |
print self._conn | |
if self._conn: | |
for key in self._conn: | |
self._conn[key].disconnect() | |
self._conn = {} | |
G_CONN = CMongo() | |
if __name__ == '__main__': | |
mongo = G_CONN[('10.2.4.1', 27017)] | |
while True: | |
time.sleep(2) | |
mongo = G_CONN[('10.2.4.1', 27017)] | |
print mongo | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment