springboot使用SSE

1、pom文件 

 
      org.springframework.boot
      spring-boot-starter-web
 

2、前端代码




    
     Springboot集成SSE 




3、后端代码

1、订阅

private static Map cache = new ConcurrentHashMap<>();
	@GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
	public SseEmitter subscribe(@RequestParam(name = "id", required = false) String id) throws IOException {
		// 超时时间设置
		SseEmitter sseEmitter = new SseEmitter(0L);
		// 设置前端的重试时间为1s
		sseEmitter.send(SseEmitter.event().reconnectTime(1000).data("连接成功"));
		cache.put(id, sseEmitter);
		System.out.println("add " + id);
		sseEmitter.onTimeout(() -> {
			System.out.println(id + "超时");
			cache.remove(id);
		});
		sseEmitter.onCompletion(() -> System.out.println("完成!!!"));
		return sseEmitter;
	}

2、推送

@GetMapping(path = "push")
	public String push(@RequestParam(name = "content", required = false) String content) throws IOException {
		SseEmitter sseEmitter = cache.get("123");
		if (sseEmitter != null) {
			sseEmitter.send(SseEmitter.event().name("msg").data("后端发送消息:" + content));
		}
		return "over";
	}

3、关闭

@GetMapping(path = "over")
	public String over(@RequestParam(name = "id", required = false) String id) {
		SseEmitter sseEmitter = cache.get(id);
		if (sseEmitter != null) {
			sseEmitter.complete();
			cache.remove(id);
		}
		return "over";
	}

你可能感兴趣的:(spring,boot,java,后端)