gpt4 book ai didi

spring - 使用 Spring 的 DeferredResult 进行长轮询

转载 作者:IT老高 更新时间:2023-10-28 13:46:57 28 4
gpt4 key购买 nike

客户端定期调用异步方法(长轮询),向其传递股票代码的值,服务器使用该值查询数据库并将对象返回给客户端。

我正在使用 Spring 的 DeferredResult类,但是我不熟悉它是如何工作的。请注意我如何使用符号属性(从客户端发送)来查询数据库以获取新数据(见下文)。

也许有更好的方法来使用 Spring 进行长轮询?

如何将符号属性从方法 deferredResult() 传递给 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);
}
}

最佳答案

DeferredResult在 Spring 4.1.7 中:

Subclasses can extend this class to easily associate additional data or behavior with the DeferredResult. For example, one might want to associate the user used to create the DeferredResult by extending the class and adding an additional property for the user. In this way, the user could easily be accessed later without the need to use a data structure to do the mapping.

您可以扩展 DeferredResult 并将符号参数保存为类字段。

static class DeferredQuote extends DeferredResult<Quote> {
private final String symbol;
public DeferredQuote(String symbol) {
this.symbol = symbol;
}
}

@RequestMapping("/poll/{symbol}")
public @ResponseBody DeferredQuote deferredResult(@PathVariable("symbol") String symbol) {
DeferredQuote result = new DeferredQuote(symbol);
responseBodyQueue.add(result);
return result;
}

@Scheduled(fixedRate = 2000)
public void processQueues() {
for (DeferredQuote result : responseBodyQueue) {
Quote quote = jpaStockQuoteRepository.findStock(result.symbol);
result.setResult(quote);
responseBodyQueue.remove(result);
}
}

关于spring - 使用 Spring 的 DeferredResult 进行长轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31458910/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com