SseController.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.genersoft.iot.vmp.gb28181.controller;
  2. import com.genersoft.iot.vmp.gb28181.event.alarm.AlarmEventListener;
  3. import io.swagger.v3.oas.annotations.tags.Tag;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import javax.annotation.Resource;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.io.IOException;
  11. import java.io.PrintWriter;
  12. /**
  13. * SSE 推送.
  14. *
  15. * @author lawrencehj
  16. * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
  17. * @since 2021/01/20
  18. */
  19. @Tag(name = "SSE 推送")
  20. @RestController
  21. @RequestMapping("/api")
  22. public class SseController {
  23. @Resource
  24. private AlarmEventListener alarmEventListener;
  25. /**
  26. * SSE 推送.
  27. *
  28. * @param response 响应
  29. * @param browserId 浏览器ID
  30. * @throws IOException IOEXCEPTION
  31. * @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>
  32. * @since 2023/11/06
  33. */
  34. @GetMapping("/emit")
  35. public void emit(HttpServletResponse response, @RequestParam String browserId) throws IOException, InterruptedException {
  36. response.setContentType("text/event-stream");
  37. response.setCharacterEncoding("utf-8");
  38. PrintWriter writer = response.getWriter();
  39. alarmEventListener.addSseEmitter(browserId, writer);
  40. while (!writer.checkError()) {
  41. Thread.sleep(1000);
  42. writer.write(":keep alive\n\n");
  43. writer.flush();
  44. }
  45. alarmEventListener.removeSseEmitter(browserId, writer);
  46. }
  47. }