Spring sseEmitter,在调用方法发送后不会立即发送事件

时间:2015-12-09 00:50:20

标签: java spring spring-mvc server-sent-events

我正在尝试使用Spring 4(tomcat 7,servlet-api 3.0.1)创建服务器发送的事件。

问题是我的Events在调用方法发送后没有立即发送。只有在SseEmitter超时后,它们才会同时(具有相同的时间戳)到达客户端,并出现EventSource的错误事件。然后客户端正在尝试重新连接。知道发生了什么吗?

我创建了一个简单的服务:

@RequestMapping(value = "subscribe", method = RequestMethod.GET)
public SseEmitter subscribe () throws IOException {
    final SseEmitter emitter = new SseEmitter();
    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            try {
                emitter.send(SseEmitter.event().data("Thread writing: " + Thread.currentThread()).name("ping"));
            } catch (Exception e) {
            }
        }
    } , 1000, 1000, TimeUnit.MILLISECONDS);
    return emitter;
}

使用客户端代码:

sse = new EventSource(urlBuilder(base, url));
sse.addEventListener('ping', function (event) {
    dfd.notify(event);
});

sse.addEventListener('message', function(event){
    dfd.notify(event);
});

sse.addEventListener('close', function(event){
    dfd.notify(event);
});

sse.onerror = function (error) {
    console.log(error);
};

sse.onmessage = function (event){
    dfd.notify(event);
};

App initalizer代码

public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(servletContext);
        ctx.refresh();

        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        dynamic.setAsyncSupported(true);
        dynamic.addMapping("/api/*");
        dynamic.setLoadOnStartup(1);
        dynamic.setMultipartConfig(ctx.getBean(MultipartConfigElement.class));

        javax.servlet.FilterRegistration.Dynamic filter = servletContext
                .addFilter("StatelessAuthenticationFilter",
                        ctx.getBean("statelessAuthenticationFilter", StatelessAuthenticationFilter.class));
        filter.setAsyncSupported(true);
        filter.addMappingForUrlPatterns(null, false, "/api/*");

        filter = servletContext.addFilter("HibernateSessionRequestFilter",
                ctx.getBean("hibernateSessionRequestFilter", HibernateSessionRequestFilter.class));
        filter.setAsyncSupported(true);
        filter.addMappingForUrlPatterns(null, false, "/api/user/*");
    }
}

AppConfig.java

@Configuration
@ComponentScan("ru.esoft.workflow")
@EnableWebMvc
@PropertySource({"classpath:mail.properties", "classpath:fatclient.properties"})
@EnableAsync
@EnableScheduling
public class AppConfig extends WebMvcConfigurerAdapter {
...
}

我的客户日志的图片: enter image description here

2 个答案:

答案 0 :(得分:3)

我在测试SSEEmitters时遇到了这个问题。从我在线阅读的所有内容中,SSEEmitters旨在与Reactive Streams的某些实现结合使用,例如RxJava。它有点复杂,但绝对有效。我们的想法是创建发射器和Observable,并将后者订阅到Publisher。 Publisher在单独的线程中执行其行为,在输出准备就绪时通知Observable,并且observable触发emitter.send。以下是一个示例代码段,可以执行您想要的操作:

priv/static/.well-known/acme-challenge/(some-unique-string)

以下是相应的发布商:

@RequestMapping("/whatever")
public SseEmitter index(    
    SseEmitter emitter = new SseEmitter();
    Publisher<String> responsePublisher = someResponseGenerator.getPublisher();
    Observable<String> responseObservable = RxReactiveStreams.toObservable(responsePublisher);

    responseObservable.subscribe(
        str -> {
            try {
                emitter.send(str);
            } catch (IOException ex) {
                emitter.completeWithError(ex);
            }
        },
        error -> {
            emitter.completeWithError(error);
        },
        emitter::complete
        );

        return emitter;
};

此模型有一些在线herehere的示例,您可以通过Google搜索RxJava SseEmitter找到更多信息。&#39; RxJava SseEmitter&#39;需要一些时间才能完成Reactive Streams / RxJava / SseEmitter交互,但是一旦你这样做就非常优雅了。希望这能让你走上正确的道路!

答案 1 :(得分:0)

虽然另一个答案是正确的,但如果您想自己管理,可以致电:

emitter.complete()