我正在尝试设置Spring SseEmitter以发送正在运行的作业状态的一系列更新。似乎可行,但是:
每当我在Java服务器代码中调用emitter.complete()
时,javascript EventSource
客户端都会调用已注册的onerror
函数,然后使用新连接再次调用Java端点。 Firefox和Chrome都会发生这种情况。
我可能可以从Java发送明确的“数据终止”消息,然后检测到该消息并在客户端上调用eventSource.close()
,但是还有更好的方法吗?
在这种情况下,emitter.complete()
的目的是什么?
此外,如果我总是必须在客户端上终止连接,那么我想服务器端的每个连接都将因超时或写入错误而终止,在这种情况下,我可能想手动发回一个每隔几秒钟就会有某种心跳吗?
如果我必须做所有这些事情,那感觉就像是缺少了一些东西。
答案 0 :(得分:0)
我已在Spring启动应用程序中添加了以下内容,以触发SSE连接close()
服务器端:
完成后,通过SseEmitter发送一个类型为complete的事件。
@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;
}
}
客户端:
name
上指定了事件SseEmitter
,因此将在浏览器上将事件分派给侦听器以获取指定的事件名称;网站源代码应使用addEventListener()
来监听命名事件。 (注意:如果未为消息指定事件名称,则调用onmessage
处理程序)EventSource
事件上调用COMPLETE
,以释放客户端连接。 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();
});