【问题标题】:Spring Long Polling with DeferredResult带有 DeferredResult 的春季长轮询
【发布时间】:2015-10-19 10:09:41
【问题描述】:

我有一个 Spring MVC 3.2 应用程序,我需要向这个 Web 服务添加一个长轮询以进行实时聊天。 我关注了这篇文章Spring MVC 3.2 Preview: Chat Sample

TopicRestController:

 private final Map<DeferredResult<String>, Long> chatRequests =
            new ConcurrentHashMap<DeferredResult<String>, Long>();

 @RequestMapping(value="/{topicId}/updates" , method=RequestMethod.POST)
public @ResponseBody DeferredResult<String> isNewTopic(
        @PathVariable Long topicId,
        Model model, HttpSession session,
        @RequestParam(required = true) String data) throws InterruptedException, CircularDefinitionException{
    logger.info("New long polling request "+topicId);
    final DeferredResult<String> result = new DeferredResult<String>();
    this.chatRequests.put(result, topicId);

    result.onCompletion(new Runnable() {
        @Override
        public void run() {
            chatRequests.remove(result);
            logger.info("Remove request from queue!");
        }
      });

        Timestamp timestamp = new Timestamp(Long.valueOf(data)*1000L);
        String updates = talkService.findNewTopicResponce(topicId,timestamp);
        if (!updates.isEmpty()) {
            result.setResult(updates);
        }

    return result;
}

@RequestMapping(value= "/{categoryId}" + "/addAnswer", method=POST) 
public @ResponseBody Map respTopic(
        @PathVariable Long categoryId,
        @RequestParam String msg,
        @RequestParam(required = false) String imageUrl,
        @RequestParam(required = false) String title,
        @RequestParam long talkId,
        HttpServletRequest request
        ) throws CircularDefinitionException, MessagingException,TalkNotExistException{
     ........................
    for (Entry<DeferredResult<String>, Long> entry :  this.chatRequests.entrySet()){
                            if(entry.getValue().equals(talkId)){        
                                entry.getKey().setResult(""+talkId);
                            }
                        }

    }

现在的问题是:

当我调用“/{topicId}/updates”时,如果 30 秒后没有任何答案,服务器返回错误 500,如果有人写了一条消息,服务器返回正确的消息,但服务器总是在 30 秒后响应,我需要服务器在有人写新消息时立即响应,而不是在超时过程中。

【问题讨论】:

    标签: spring spring-mvc asynchronous long-polling


    【解决方案1】:

    我刚遇到同样的问题,遇到了类似的问题:Tomcat 7 server error after 10 seconds when long polling

    基本上,您必须告诉 Tomcat 不要超时。为此,您可以编辑 server.xml Tomcat 文件(在您的 conf 目录中)以包含 asyncTimeout 参数。这会告诉你的 Tomcat 在一分钟后超时:

    &lt;Connector port="8080" protocol="HTTP/1.1" asyncTimeout="60000" connectionTimeout="20000" redirectPort="8443" /&gt;

    使用值 -1 告诉 Tomcat 永远不会超时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      相关资源
      最近更新 更多