SSE 事件源每 5 秒收到一次"打开"和"打开错误"事件



我正在使用js EventSource和spring SseEmitter实现SSE流,但是每5秒就会引发"onerror",然后引发"onopen"事件。

这是服务器端控制器:

@RestController
public class SseController
{   
    @Autowired
    SseService sseService;
    @GetMapping(path = "/sseChannel/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter openSseChannelForUser(@PathVariable int userId)
    {
        SseEmitter sseEmitter = new SseEmitter();
        sseService.addSse(userId, sseEmitter);
        return sseEmitter;
    }
}

这是javascript:

var sseClient = null;
function sseInit(userId) 
{
    var url = '/app/spring/sseChannel/'+userId;
    sseClient = new EventSource(url);
    sseClient.onopen = function () 
    {
        console.log("onopen() ");
    };
    sseClient.onmessage = function (evt) 
    {
        console.log("onmessage() "+ evt.data);
    };
    sseClient.onerror = function (evt) 
    {
        console.log("onerror() ");
    };
}

这是控制台:

onopen() 
onerror() 
onopen() 
onerror() 
onopen() 
onerror() 
onopen() 
onerror()
.
.
.

这是超时

@GetMapping(path = "/sseChannel/{userId}"/* , produces = MediaType.TEXT_EVENT_STREAM_VALUE */)
    public SseEmitter openSseChannelForUser(@PathVariable int userId)
    {
        Long timeout = (long) (1000*60);
        SseEmitter sseEmitter = new SseEmitter(timeout);
        sseService.addSse(userId, sseEmitter);
         sseEmitter.onCompletion(() -> {
             synchronized (new Object()) {
                 sseService.removeSse(userId);
             }
         });
         sseEmitter.onTimeout(()-> {
             sseEmitter.complete();
         });
        return sseEmitter;
    }

最新更新