DeferredResult不是轮询

时间:2014-09-26 13:36:10

标签: spring asynchronous spring-io

我正在尝试使用https://github.com/rstoyanchev/spring-mvc-chat

中的基本示例创建多用户聊天环境

我无法找到我的代码到底出了什么问题。请求不轮询它只是持续向服务器发送请求。

以下是我的代码snipets

的web.xml

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

的applicationContext.xml

<mvc:annotation-driven>
    <mvc:async-support default-timeout="30000" />
    <mvc:message-converters register-defaults="false">
        <bean id="jacksonMessageConverter"
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
    </mvc:message-converters>
</mvc:annotation-driven>

控制器

@Controller
@RequestMapping("/chat")
public class ChatController
{
    @RequestMapping("messages")
    @ResponseBody
    public DeferredResult<List<String>> getMessages()
    {

        final DeferredResult<List<String>> deferredResult = new DeferredResult<List<String>>(30000l, Collections.emptyList());
        this.chatRequests.put(deferredResult, 0);

        deferredResult.onCompletion(new Runnable()
        {
            @Override
            public void run()
            {
                chatRequests.remove(deferredResult);
            }
        });

        List<String> messages = new ArrayList<String>();
        messages.add("first");
        if (!messages.isEmpty())
        {
            deferredResult.setResult(messages);
        }

        return deferredResult;
    }

}

的javascript

function chatModel(){
var started = false;
var that = this;
that.activePollingXhr = ko.observable(null);
function pollForMessages() {
    that.activePollingXhr($.ajax({
        url : contextPath + '/chat/messages',
        type : "GET",
        cache : false,
        success : function(messages) {
            console.log(messages);
        },
        error : function(xhr) {
            if (xhr.statusText != "abort" && xhr.status != 503) {
                console.log('Unable to Connect');
            }
        },
        complete : pollForMessages
    }));
}

1 个答案:

答案 0 :(得分:0)

遇到了问题。 如果我们设定结果

deferredResult.setResult();

它不要等待,所以进入递归调用。