我經常需要用Python與solr進行異步請求工作。這里有段代碼阻塞在Solr http請求上, 直到第一個完成才會執行第二個請求,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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庫進行http請求)
通過腳本把文檔索引到Solr, 進而可以并行工作是很好的。我需要擴展我的工作,因此索引瓶頸是Solr,而不是網絡請求。
不幸的是,當進行異步編程時python不像Javascript或Go那樣方便。但是,gevent庫能給我們帶來些幫助。gevent底層用的是libevent庫,構建于原生異步調用(select, poll等原始異步調用),libevent很好的協調很多低層的異步功能。
使用gevent很簡單,讓人糾結的一點就是thegevent.monkey.patch_all(), 為更好的與gevent的異步協作,它修補了很多標準庫。聽起來很恐怖,但是我還沒有在使用這個補丁實現時遇到 問題。
事不宜遲,下面就是你如果用gevents來并行Solr請求:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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代碼簡潔,但是它能完成相應的工作,代碼的精髓是下面幾行:
1
2
3
4
5
6
7
|
# 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產生searcher.search, 我們可以對產生的任務進行操作,然后我們可以隨意的等著所有產生的任務完成,最后導出結果。
差不多就這樣子.如果你有任何想法請給我們留言。讓我們知道我們如何能為你的Solr搜索應用提供幫助。