JAX-RS SSE 连接突然关闭

问题描述 投票:0回答:0

我正在尝试使用 JAX-RS 使用以下代码创建 SSE:

import java.util.List;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.sse.OutboundSseEvent;
import javax.ws.rs.sse.Sse;
import javax.ws.rs.sse.SseEventSink;

@Path("events")
public class EventsHandler {

    
    Executor executorService = Executors.newSingleThreadExecutor();
    @GET
    @Produces(MediaType.SERVER_SENT_EVENTS)
    public void sendEvents(@Context SseEventSink sseEventSink, @Context Sse sse) {
        Random rnd = new Random();
        IntStream rndStream = IntStream.generate(() -> rnd.nextInt(90));
        List<Integer> lottery = rndStream.limit(5).boxed().collect(Collectors.toList());
        executorService.execute(() -> {
            lottery.forEach(value -> {
                try {
                    TimeUnit.SECONDS.sleep(5);
                    System.out.println("Sending the following value: " + value);
                    final OutboundSseEvent outboundSseEvent = sse.newEventBuilder().name("lottery")
                            .data(Integer.class, value).build();
                    sseEventSink.send(outboundSseEvent);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
            sseEventSink.close();
        });
    }
}

但是,每次尝试在我的 Wildfly 服务器上运行它都会抛出消息

Failed to set servlet request into asynchronous mode, server sent events may not work
,没有更多详细信息。

我尝试将 servlet 配置中的 asyncSupport 更改为 true,但没有效果。

java servlets jax-rs server-sent-events
© www.soinside.com 2019 - 2024. All rights reserved.