在Python的gevent框架下執(zhí)行異步的Solr查詢的教程
我經(jīng)常需要用Python與solr進(jìn)行異步請求工作。這里有段代碼阻塞在Solr http請求上, 直到第一個完成才會執(zhí)行第二個請求,代碼如下:
import requests
#Search 1
solrResp = requests.get('http://mysolr.com/solr/statedecoded/search?q=law')
for doc in solrResp.json()['response']['docs']:
print doc['catch_line']
#Search 2
solrResp = requests.get('http://mysolr.com/solr/statedecoded/search?q=shoplifting')
for doc in solrResp.json()['response']['docs']:
print doc['catch_line']
(我們用Requests庫進(jìn)行http請求)
通過腳本把文檔索引到Solr, 進(jìn)而可以并行工作是很好的。我需要擴(kuò)展我的工作,因此索引瓶頸是Solr,而不是網(wǎng)絡(luò)請求。
不幸的是,當(dāng)進(jìn)行異步編程時python不像Javascript或Go那樣方便。但是,gevent庫能給我們帶來些幫助。gevent底層用的是libevent庫,構(gòu)建于原生異步調(diào)用(select, poll等原始異步調(diào)用),libevent很好的協(xié)調(diào)很多低層的異步功能。
使用gevent很簡單,讓人糾結(jié)的一點就是thegevent.monkey.patch_all(), 為更好的與gevent的異步協(xié)作,它修補(bǔ)了很多標(biāo)準(zhǔn)庫。聽起來很恐怖,但是我還沒有在使用這個補(bǔ)丁實現(xiàn)時遇到 問題。
事不宜遲,下面就是你如果用gevents來并行Solr請求:
import requests
from gevent import monkey
import gevent
monkey.patch_all()
class Searcher(object):
""" Simple wrapper for doing a search and collecting the
results """
def __init__(self, searchUrl):
self.searchUrl = searchUrl
def search(self):
solrResp = requests.get(self.searchUrl)
self.docs = solrResp.json()['response']['docs']
def searchMultiple(urls):
""" Use gevent to execute the passed in urls;
dump the results"""
searchers = [Searcher(url) for url in urls]
# Gather a handle for each task
handles = []
for searcher in searchers:
handles.append(gevent.spawn(searcher.search))
# Block until all work is done
gevent.joinall(handles)
# Dump the results
for searcher in searchers:
print "Search Results for %s" % searcher.searchUrl
for doc in searcher.docs:
print doc['catch_line']
searchUrls = ['http://mysolr.com/solr/statedecoded/search?q=law',
'http://mysolr.com/solr/statedecoded/search?q=shoplifting']
searchMultiple(searchUrls)
代碼增加了,而且不如相同功能的Javascript代碼簡潔,但是它能完成相應(yīng)的工作,代碼的精髓是下面幾行:
# Gather a handle for each task handles = [] for searcher in searchers: handles.append(gevent.spawn(searcher.search)) # Block until all work is done gevent.joinall(handles)
我們讓gevent產(chǎn)生searcher.search, 我們可以對產(chǎn)生的任務(wù)進(jìn)行操作,然后我們可以隨意的等著所有產(chǎn)生的任務(wù)完成,最后導(dǎo)出結(jié)果。
差不多就這樣子.如果你有任何想法請給我們留言。讓我們知道我們?nèi)绾文転槟愕腟olr搜索應(yīng)用提供幫助。
- python3中celery異步框架簡單使用+守護(hù)進(jìn)程方式啟動
- python 5個頂級異步框架推薦
- python異步Web框架sanic的實現(xiàn)
- 關(guān)于Python核心框架tornado的異步協(xié)程的2種方法詳解
- 200行自定義python異步非阻塞Web框架
- Python的Tornado框架實現(xiàn)異步非阻塞訪問數(shù)據(jù)庫的示例
- Python的Tornado框架的異步任務(wù)與AsyncHTTPClient
- Python的Twisted框架上手前所必須了解的異步編程思想
- Python的Tornado框架異步編程入門實例
- 簡單介紹Python的Tornado框架中的協(xié)程異步實現(xiàn)原理
- python 常用的異步框架匯總整理
相關(guān)文章
Python+request+unittest實現(xiàn)接口測試框架集成實例
這篇文章主要介紹了Python+request+unittest實現(xiàn)接口測試框架集成實例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
python安裝virtualenv虛擬環(huán)境步驟圖文詳解
這篇文章主要介紹了python安裝virtualenv虛擬環(huán)境步驟,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09

