2013-07-12 60 views
1

我應該重新初始化每個插入的連接嗎?使用python將數據插入到mongodb中

class TwitterStream: 
    def __init__(self, timeout=False): 
    while True: 
    dump_data() 

    def dump_data: 
    ##dump my data into mongodb  
    ##should I be doing this every time??: 
    client=MongoClient() 
    mongo=MongoClient('localhost',27017) 
    db=mongo.test 
    db.insert('some stuff':'other stuff') 
    ##dump data and close connection 
    ######################### 

我是否需要打開每次連接我寫了一個記錄?或者我可以讓一個連接斷開,假設我將每秒鐘以每次10KB的速度寫入數據庫5次?

如果只有一個連接就夠了,我應該在哪裏定義保存連接的變量(clientmongo,db)?

回答

0

打開連接通常是一個昂貴的操作,所以我建議您儘可能重複使用它們。

在MongoClient的情況下,您應該能夠保持連接處於打開狀態並繼續重用它。但是,隨着連接時間的延長,最終你會開始觸及連接問題。爲此,建議將MongoClient配置爲使用自動重新連接的解決方案,並捕獲AutoReconnect異常作爲重試機制的一部分。

這裏說的方法的一個例子,從http://python.dzone.com/articles/save-monkey-reliably-writing採取:

while True: 
    time.sleep(1) 
    data = { 
     'time': datetime.datetime.utcnow(), 
     'oxygen': random.random() 
    } 

    # Try for five minutes to recover from a failed primary 
    for i in range(60): 
     try: 
      mabel_db.breaths.insert(data, safe=True) 
      print 'wrote' 
      break # Exit the retry loop 
     except pymongo.errors.AutoReconnect, e: 
      print 'Warning', e 
      time.sleep(5) 
+0

非常感謝你爲你的偉大的答案。你能爲我指出一些例子嗎?一直在你的立場你在說什麼,我不知道如何執行。 –

1

打開一個MongoClient一種生活爲你的程序的持續時間:

client = MongoClient() 

class TwitterStream: 
    def dump_data: 
     while True: 
      db = client.test 
      db.insert({'some stuff': 'other stuff'}) 

打開一個MongoClient意味着你只支付其啓動成本一次,其連接池將最小化打開新連接的成本。

如果你關心倖存偶爾的網絡問題,包您的操作中異常塊:

try: 
    db.insert(...) 
except pymongo.errors.ConnectionFailure: 
    # Handle error. 
    ... 
相關問題