使用Spring的DeferredResult进行长轮询 [英] Long Polling with Spring's DeferredResult

查看:535
本文介绍了使用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.

我正在使用Spring的

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);
        }
    }

推荐答案

子类可以扩展此类,以轻松地将其他数据或行为与DeferredResult相关联.例如,您可能想通过扩展类并为该用户添加其他属性来关联用于创建DeferredResult的用户.这样,以后就可以轻松访问用户,而无需使用数据结构进行映射.

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并将符号参数保存为类字段.

You can extend DeferredResult and save the symbol parameter as a class field.

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的DeferredResult进行长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆