Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

682
Views
Spring Server Sent Events - ResponseBodyEmitter ya está configurado como completo

Estoy usando Spring 4.3.7.RELEASE para configurar los eventos enviados por el servidor. Y usó la anotación @scheduled para enviar mensajes cada 2 segundos. Aquí está el controlador.

 @Controller public class MySSEController { private final SseEmitter sseEmitter = new SseEmitter(); private int counter = 0; @RequestMapping("/ssestream") public SseEmitter getRealTimeMessageAction() throws IOException { sseEmitter.send("MessageCounter : " + counter); return sseEmitter; } @Scheduled(fixedDelay = 2*1000) public void scheduledMsgEmitter() throws IOException { if(null != sseEmitter) { sseEmitter.send("MessageCounter : " + ++counter); } } }

Estoy ejecutando esto en Tomcat 9 directamente desde eclipse. La aplicación se inicia y envía mensajes al navegador cada 2 segundos. Pero después de un tiempo deja de enviar mensajes y veo la siguiente excepción en la consola de Eclipse.

 Mar 16, 2017 6:57:34 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleAsyncRequestTimeoutException SEVERE: Async timeout for GET [/streaming-web/stream/ssestream] Mar 16, 2017 6:57:35 PM org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler handleError SEVERE: Unexpected error occurred in scheduled task. java.lang.IllegalStateException: ResponseBodyEmitter is already set complete at org.springframework.util.Assert.state(Assert.java:70) at org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter.send(ResponseBodyEmitter.java:158) at org.springframework.web.servlet.mvc.method.annotation.SseEmitter.send(SseEmitter.java:126) at org.springframework.web.servlet.mvc.method.annotation.SseEmitter.send(SseEmitter.java:107) at org.springframework.web.servlet.mvc.method.annotation.SseEmitter.send(SseEmitter.java:89) at com.mycomp.test.controllers.MySSEController.scheduledMsgEmitter(MySSEController.java:25) at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)

¿Me estoy perdiendo de algo? Porfavor ayudame a resolver este problema.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

No estoy seguro de si es la solución correcta.

Modifiqué ligeramente la implementación para que funcione con todos los clientes conectados . Anteriormente, no podía enviar el mismo mensaje a diferentes clientes conectados a esta transmisión . Esta implementación no arroja IllegalStateException .

 import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; @Controller public class MySSEController_Working { private Set<SseEmitter> sseEmitters = new HashSet<SseEmitter>(); private int messageCount = 0; @RequestMapping("/ssestream") public SseEmitter getRealTimeMessageAction(HttpServletRequest request, HttpServletResponse response) throws IOException { final SseEmitter sseEmitter = new SseEmitter(); sseEmitter.onCompletion(() -> { synchronized (this.sseEmitters) { this.sseEmitters.remove(sseEmitter); } }); sseEmitter.onTimeout(()-> { sseEmitter.complete(); }); // Put context in a map sseEmitters.add(sseEmitter); return sseEmitter; } @Scheduled(fixedDelay = 2*1000) public void scheduledMsgEmitter() throws IOException { if(!sseEmitters.isEmpty()) ++messageCount; else System.out.println("No active Emitters "); System.out.println("Sent Messages : " + messageCount); sseEmitters.forEach(emitter -> { if (null != emitter) try { System.out.println("Timeout : "+ emitter.getTimeout()); emitter.send("MessageCounter : " + messageCount); emitter.complete(); } catch (IOException e) { e.printStackTrace(); } }); } }
about 4 years ago · Santiago Trujillo Report

0

El tiempo de espera de SseEmitter está en milisegundos: 60001 son 60 segundos. Es un tiempo de espera de sesión, no afectado por la actividad en la sesión.

El tiempo de espera debe establecerse en la duración esperada de la sesión, en milisegundos. Entonces, 86400000 (o más) es completamente apropiado.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!