在Python的gevent框架下执行异步的Solr查询的教程

(编辑:jimmy 日期: 2024/10/3 浏览:2)

 我经常需要用Python与solr进行异步请求工作。这里有段代码阻塞在Solr http请求上, 直到第一个完成才会执行第二个请求,代码如下:
 

import requests
 
#Search 1
solrResp = requests.get('http://mysolr.com/solr/statedecoded/search"_blank" href="http://www.oschina.net/p/gevent">gevent库能给我们带来些帮助。gevent底层用的是libevent库,构建于原生异步调用(select, poll等原始异步调用),libevent很好的协调很多低层的异步功能。

使用gevent很简单,让人纠结的一点就是thegevent.monkey.patch_all(), 为更好的与gevent的异步协作,它修补了很多标准库。听起来很恐怖,但是我还没有在使用这个补丁实现时遇到 问题。


事不宜迟,下面就是你如果用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"htmlcode">
# 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搜索应用提供帮助。

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。