SseEmitterService.java 990 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package com.rf.AIquantum.utils;
  2. /**
  3. * @Author:zzf
  4. * @Date:2025/3/10:18:25
  5. * @Description:
  6. */
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
  9. import java.util.Map;
  10. import java.util.concurrent.ConcurrentHashMap;
  11. @Component
  12. public class SseEmitterService {
  13. private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
  14. public void addEmitter(String clientId, SseEmitter emitter) {
  15. emitters.put(clientId, emitter);
  16. }
  17. public void removeEmitter(String clientId) {
  18. emitters.remove(clientId);
  19. }
  20. public void sendMessage(String clientId, Object message) {
  21. SseEmitter emitter = emitters.get(clientId);
  22. if (emitter != null) {
  23. try {
  24. emitter.send(message);
  25. } catch (Exception e) {
  26. // 处理异常,如网络问题等
  27. emitters.remove(clientId);
  28. }
  29. }
  30. }
  31. }