【问题标题】:Spring And EventSourceSpring 和 EventSource
【发布时间】:2016-02-29 20:50:26
【问题描述】:

我正在尝试向我的网站发送通知。 我的 EventSource 不会保持打开状态。它无限期地关闭和打开。 它不会在几秒钟内保持打开状态。

Javascript

this.subscribe = function(eid, cid) {
        if (!!window.EventSource) {
            //no authentication. Be carreful
            source = new EventSource(config.apiUrl + "v1/e/" + eid + "/c/" + cid + "/sse");
            source.onerror = error;
            source.addEventListener('message', function(e) {
                console.log(e.data);
            }, false);

            source.addEventListener('open', function(e) {
                // Connection was opened.
                console.log(e.data);
            }, false);

            source.addEventListener('error', function(e) {
                if (e.readyState == EventSource.CLOSED) {
                    // Connection was closed.
                }
            }, false);
        } else {
            // Result to xhr polling :(
            console.log("No notifications available");
        }
    }

Java部分

SseEmitter subscribeUpdates() {
    SseEmitter sseEmitter = new SseEmitter();
    synchronized (this.sseEmitters) {
        this.sseEmitters.add(sseEmitter);
        sseEmitter.onCompletion(() -> {
            synchronized (this.sseEmitters) {
                this.sseEmitters.remove(sseEmitter);
            }
        });
    }
    return sseEmitter;
}

有什么想法吗?

提前致谢。


在没有任何线索的情况下,我设法以不同的方式做事。 我有一个 NodeJS 服务器,它提供诸如 SSE、Websocket 和其他实时内容之类的东西。 我的 Spring 应用程序只是将事件发送到 nodeJS,然后将其发送给客户端。

【问题讨论】:

    标签: javascript spring spring-mvc eventsource


    【解决方案1】:

    使用您选择的有效负载从 JAVA 发送消息以指示不再有数据:

    source.addEventListener('message', function(e) {
        if ('END-OF-STREAM' == e.data) {
            source.close(); // stop retry
        }
        console.log(e.data);
    }, false);
    

    【讨论】:

      【解决方案2】:

      您需要像这样为 SseEmitter 定义超时: SseEmitter sseEmitter = new SseEmitter(300000L); // 5 min

      【讨论】:

        猜你喜欢
        • 2021-02-14
        • 1970-01-01
        • 2019-02-09
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多