2011-07-08 18 views
1

由于某种原因,我们计划在我们的项目中使用kestrel队列。我们做一些恶魔,主要的问题是如何从CPU利用率低的队列中获取数据,并且有效。我们实现获取的方式是,如果我们无法从队列中获取数据超过5次,我们会将线程休眠100ms以降低CPU利用率。如何从kestrel队列有效提取数据

while (running) { 
      try { 
       LoginLogQueueEntry data = kestrelQueue.fetch(); 
       if (null != data && data.isLegal()) { 
        entryCacheList.add(data); //add the data to the local caceh 
        resetStatus(); 
       } else { 
        failedCount++; 
        //if there is no data in the kestrel and the local cache is not empty, insert the data into mysql database 
        if (failedCount == 1 && !entryCacheList.isEmpty()) { 
         resetStatus(); 
         insertLogList(entryCacheList); // insert current data into database 
         entryCacheList.clear(); //empty local cache 
        } 

        if (failedCount >= 5 && entryCacheList.isEmpty()) { 
        //fail 5 times. Sleep current thread. 
         failedCount = 0; 
         Thread.sleep((sleepTime + MIN_SLEEP_TIME) % MAX_SLEEP_TIME); 
        } 
       } 
       //Insert 1000 rows once 
       if (entryCacheList.size() >= 1000) { 
        insertLogList(entryCacheList); 
        entryCacheList.clear(); 
       } 
      } catch (Exception e) { 
       logger.warn(e.getMessage()); 
      } 

有没有其他的好办法呢?我认为完美的方式是通过队列可以通知工作人员我们获取数据并获取数据。

回答

-1

你需要使用阻塞get。我无法追踪API文档,但我发现一篇文章暗示它可能在红隼中。

2

挡住了“阻止抓取操作”部分读取,这里所描述的,“内存缓存命令”下:https://github.com/robey/kestrel/blob/master/docs/guide.md

您可以通过用斜线分开添加选项标志的get命令,所以从“工作”队列中取出一个项目,等待了一秒:

get jobs/t=1000 

如果什么也不显示在一秒钟队列,你会得到相同的空应答,只需一秒比你晚'得到它现在。 :)

当你这样做时,调整你的响应超时非常重要。如果您使用阻塞读取的时间为一秒,但客户端库的响应超时时间为500毫秒,则在阻塞读取完成之前,库将与服务器断开连接。因此,请确保响应超时大于您在读取请求中使用的超时。