使用Spring的DeferredResult进行长轮询 [英] Long Polling with Spring's DeferredResult
本文介绍了使用Spring的DeferredResult进行长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
客户端定期调用异步方法(长时间轮询),并向其传递一个股票代号的值,服务器使用该值查询数据库并将对象返回给客户端.
The client periodically calls an async method (long polling), passing it a value of a stock symbol, which the server uses to query the database and return the object back to the client.
I am using Spring's DeferredResult class, however I'm not familiar with how it works. Notice how I am using the symbol property (sent from client) to query the database for new data (see below).
也许使用Spring进行长轮询有更好的方法吗?
Perhaps there is a better approach for long polling with Spring?
如何将符号属性从方法deferredResult()
传递给processQueues()
?
How do I pass the symbol property from the method deferredResult()
to processQueues()
?
private final Queue<DeferredResult<String>> responseBodyQueue = new ConcurrentLinkedQueue<>();
@RequestMapping("/poll/{symbol}")
public @ResponseBody DeferredResult<String> deferredResult(@PathVariable("symbol") String symbol) {
DeferredResult<String> result = new DeferredResult<String>();
this.responseBodyQueue.add(result);
return result;
}
@Scheduled(fixedRate=2000)
public void processQueues() {
for (DeferredResult<String> result : this.responseBodyQueue) {
Quote quote = jpaStockQuoteRepository.findStock(symbol);
result.setResult(quote);
this.responseBodyQueue.remove(result);
}
}
推荐答案
查看全文