【问题标题】:Should Spring SseEmitter.complete() trigger an EventSource reconnect - how to close connection server-sideSpring SseEmitter.complete() 是否应该触发 EventSource 重新连接 - 如何在服务器端关闭连接
【发布时间】:2019-03-21 18:55:49
【问题描述】:

我正在尝试设置一个 Spring SseEmitter 来发送一系列正在运行的作业状态的更新。它似乎正在工作,但是:

每当我在我的 Java 服务器代码中调用 emitter.complete() 时,javascript EventSource 客户端调用已注册的 onerror 函数,然后使用新连接再次调用我的 Java 端点。这在 Firefox 和 Chrome 中都会发生。

我可能可以从 Java 发送明确的“数据结束”消息,然后检测到该消息并在客户端调用 eventSource.close(),但有更好的方法吗?

在这种情况下emitter.complete() 的目的是什么?

另外,如果我总是必须终止客户端的连接,那么我猜服务器端的每个连接都会因超时或写入错误而终止,在这种情况下,我可能想手动发回一个每隔几秒就会有某种心跳?

如果我不得不做这一切,感觉就像我错过了一些东西。

【问题讨论】:

  • 面临同样的问题,在服务器端调用发射器::完成后向端点发出新请求。 springBootVersion=2.0.5.RELEASE
  • 我得到了一些工作,但我通过发送我自己的自定义“停止”事件然后在客户端关闭它来做到这一点。

标签: java spring spring-mvc eventsource


【解决方案1】:

我已将以下内容添加到我的 Spring Boot 应用程序以触发 SSE 连接close()

服务器端:

  1. 创建一个返回 SseEmitter 的简单控制器。
  2. 将后端逻辑包装在单线程执行器服务中。
  3. 将您的事件发送到 SseEmitter。
  4. 在完成时通过 SseEmitter 发送一个完成类型的事件。

    @RestController
    public class SearchController {
    
    @Autowired
    private SearchDelegate searchDelegate;
    
    @GetMapping(value = "/{customerId}/search")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "Search Sources", notes = "Search Sources")
    @ApiResponses(value = {
            @ApiResponse(code = 201, message = "OK"),
            @ApiResponse(code = 401, message = "Unauthorized")
    })
    @ResponseBody
    public SseEmitter search(@ApiParam(name = "searchCriteria", value = "searchCriteria", required = true) @ModelAttribute @Valid final SearchCriteriaDto searchCriteriaDto) throws Exception {
        return searchDelegate.route(searchCriteriaDto);
      }
    }
    
    
    
    @Service
    public class SearchDelegate {
    public static final String SEARCH_EVENT_NAME = "SEARCH";
    public static final String COMPLETE_EVENT_NAME = "COMPLETE";
    public static final String COMPLETE_EVENT_DATA = "{\"name\": \"COMPLETED_STREAM\"}";
    
    @Autowired
    private SearchService searchService;
    
    private ExecutorService executor = Executors.newCachedThreadPool();
    
    public SseEmitter route(SearchCriteriaDto searchCriteriaDto) throws Exception {
        SseEmitter emitter = new SseEmitter();
        executor.execute(() -> {
            try {
                if(!searchCriteriaDto.getCustomerSources().isEmpty()) {
                    searchCriteriaDto.getCustomerSources().forEach(customerSource -> {
                        try {
                            SearchResponse searchResponse = searchService.search(searchCriteriaDto);
                            emitter.send(SseEmitter.event()
                                    .id(customerSource.getSourceId())
                                    .name(SEARCH_EVENT_NAME)
                                    .data(searchResponse));
                        } catch (Exception e) {
                            log.error("Error while executing query for customer {} with source {}, Caused by {}",
                                    customerId, source.getType(), e.getMessage());
                        }
                    });
                }else {
                    log.debug("No available customerSources for the specified customer");
                }
                emitter.send(SseEmitter.event().
                        id(String.valueOf(System.currentTimeMillis()))
                        .name(COMPLETE_EVENT_NAME)
                        .data(COMPLETE_EVENT_DATA));
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });
        return emitter;
       }
    }
    

客户端:

  1. 由于我们在SseEmitter 上指定了name 的事件,因此将在浏览器上向指定事件名称的侦听器分派一个事件;网站源代码应该使用addEventListener() 来监听命名事件。 (注意:如果没有为消息指定事件名称,则会调用 onmessage 处理程序)
  2. 在COMPLETE 事件上调用EventSource 以释放客户端连接。

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

var sse = new EventSource('http://localhost:8080/federation/api/customers/5d96348feb061d13f46aa6ce/search?nativeQuery=true&queryString=*&size=10&customerSources=1,2,3&start=0');

sse.addEventListener("SEARCH", function(evt) {
   var data = JSON.parse(evt.data);
   console.log(data);
});

sse.addEventListener("COMPLETE", function(evt) {
   console.log(evt);
   sse.close();
});

【讨论】:

  • 这几乎就是我最终要做的。
  • 我仍然不确定emitter.complete()。我猜它只是结束服务器端的事情?因为我认为它传输的任何东西都会在客户端遇到封闭的 sse。
【解决方案2】:

根据HTML standard for Server-sent events

如果连接关闭,客户端将重新连接;可以使用 HTTP 204 No Content 响应代码告诉客户端停止重新连接。

所以 Spring 的 SseEmitter 的行为符合预期,complete() 的目的是确保所有事件都已发送,然后关闭连接。

您需要实现服务器端逻辑,该逻辑将在后续请求中返回 204 http 代码(例如,通过检查会话 id)或发送特殊事件并在接收到 suggested by Ashraf Sarhan 后从客户端关闭连接

【讨论】:

  • 哦,好的 204。这对我来说似乎比从客户端关闭更自然。
猜你喜欢
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2019-01-07
  • 2016-09-12
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多