对了,网上的pymongo教程有点老,大家可以看看pymongo的教程,别看其他的博客。如果你读了一堆,它们就已经过时了。推荐直接看官方文档,内容不多,非常容易上手。发现的问题和网上的用法不一样。目前只有MongoClient()作为连接方式,参数safe=true不存在。maxPoolSize默认为100,连接时可以自行设置。和网上说的不一样,据说插入数据时指定_id比不指定快。实际测试刚好相反,但差别不大。指定或指定logging.info()很耗时。测试插入10000条数据,加这句话大概需要16秒,加完大概需要7秒。pymongo使用importrequestsfrompymongoimportMongoClientimportloggingimporttimeimportjsonfromconcurrent.futuresimportThreadPoolExecutorlogging.basicConfig(level=logging.DEBUG,format='%(asctime)s[%(threadName)s]%(levelname)s:%(message)s')#多路复用连接可以大大提高效率s=requests.Session()#修改默认连接数(10)为20个host,200个连接池,httphttps对应各自的类型,只需要设置s.mount('https://',requests.adapters.HTTPAdapter(pool_connections=20,pool_maxsize=200))s.mount('http://',requests.adapters.HTTPAdapter(pool_connections=20,pool_maxsize=200))defgetHTML(uid):#url=''returnuiddeftoDB(obj):res=obj.result()x=collect.insert_one({'_id':res+20000,'uid':res})##添加_id好像更快,网上说的更快,都是放屁#logging.info(x.inserted_id)if__name__=="__main__":logging.info('start')#client=MongoClient('127.0.0.1',27017)#默认连接client=MongoClient('127.0.0.1',65500,maxPoolSize=200)#200连接数db=client['douyin']collect=db['user']pool=ThreadPoolExecutor()#默认为CPU数*5t=time.perf_counter()forshort_idinrange(10000):pool.submit(getHTML,short_id).add_done_callback(toDB)pool.shutdown(wait=True)client.close()t=time.perf_counter()-tprint(吨)
