Home >Java >javaTutorial >How Spring Boot uses SSE to push data to the front end
SSE is simply a technology where the server actively pushes data to the front-end. It is one-way, which means that the front-end cannot send data to the server. SSE is suitable for message push, monitoring and other scenarios that only require server push data. The following is a simple simulation using Spring Boot to push progress data to the front end. After the front end page accepts it, the progress bar is displayed.
You need to pay attention when using it in Spring Boot. It is best to use the SseEmitter class provided by Spring Web to operate. At the beginning, I used the Content-Type mentioned on the Internet. If set to text-stream, it will be found that the front end will re-create the connection every time. Finally, I achieved the final desired effect by referring to this article:
SSEServer.java
package vip.huhailong.catchat.sse; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; /** * @author Huhailong */ @Slf4j public class SSEServer { /** * 当前连接数 */ private static AtomicInteger count = new AtomicInteger(0); private static Map<String, SseEmitter> sseEmitterMap = new ConcurrentHashMap<>(); public static SseEmitter connect(String userId){ //设置超时时间,0表示不过期,默认是30秒,超过时间未完成会抛出异常 SseEmitter sseEmitter = new SseEmitter(0L); //注册回调 sseEmitter.onCompletion(completionCallBack(userId)); sseEmitter.onError(errorCallBack(userId)); sseEmitter.onTimeout(timeOutCallBack(userId)); sseEmitterMap.put(userId,sseEmitter); //数量+1 count.getAndIncrement(); log.info("create new sse connect ,current user:{}",userId); return sseEmitter; } /** * 给指定用户发消息 */ public static void sendMessage(String userId, String message){ if(sseEmitterMap.containsKey(userId)){ try{ sseEmitterMap.get(userId).send(message); }catch (IOException e){ log.error("user id:{}, send message error:{}",userId,e.getMessage()); e.printStackTrace(); } } } /** * 想多人发送消息,组播 */ public static void groupSendMessage(String groupId, String message){ if(sseEmitterMap!=null&&!sseEmitterMap.isEmpty()){ sseEmitterMap.forEach((k,v) -> { try{ if(k.startsWith(groupId)){ v.send(message, MediaType.APPLICATION_JSON); } }catch (IOException e){ log.error("user id:{}, send message error:{}",groupId,message); removeUser(k); } }); } } public static void batchSendMessage(String message) { sseEmitterMap.forEach((k,v)->{ try{ v.send(message,MediaType.APPLICATION_JSON); }catch (IOException e){ log.error("user id:{}, send message error:{}",k,e.getMessage()); removeUser(k); } }); } /** * 群发消息 */ public static void batchSendMessage(String message, Set<String> userIds){ userIds.forEach(userId->sendMessage(userId,message)); } public static void removeUser(String userId){ sseEmitterMap.remove(userId); //数量-1 count.getAndDecrement(); log.info("remove user id:{}",userId); } public static List<String> getIds(){ return new ArrayList<>(sseEmitterMap.keySet()); } public static int getUserCount(){ return count.intValue(); } private static Runnable completionCallBack(String userId) { return () -> { log.info("结束连接,{}",userId); removeUser(userId); }; } private static Runnable timeOutCallBack(String userId){ return ()->{ log.info("连接超时,{}",userId); removeUser(userId); }; } private static Consumer<Throwable> errorCallBack(String userId){ return throwable -> { log.error("连接异常,{}",userId); removeUser(userId); }; } }
The above class can be used as Make an SSE tool class, let's use it below
package vip.huhailong.catchat.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import vip.huhailong.catchat.sse.SSEServer; /** * @author Huhailong */ @Slf4j @RestController @CrossOrigin @RequestMapping("/sse") public class SSEController { @GetMapping("/connect/{userId}") public SseEmitter connect(@PathVariable String userId){ return SSEServer.connect(userId); } @GetMapping("/process") public void sendMessage() throws InterruptedException { for(int i=0; i<=100; i++){ if(i>50&&i<70){ Thread.sleep(500L); }else{ Thread.sleep(100L); } SSEServer.batchSendMessage(String.valueOf(i)); } } }
in the Controller layer. The above connect is used to connect to sse. It returns an SseEmitter instance. At this time The connection has been created, and the process interface below is used to push data. I am going to let the front end realize the effect of a progress bar, so what is pushed is a number. In order to have an obvious effect, I push it to 50 to 70. Slow down, the rest is 100ms
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> <script> let data = new EventSource("/cat-chat/sse/connect/huhailong") data.onmessage = function(event){ console.log("test=>",event) document.getElementById("result").innerText = event.data+'%'; document.getElementById("my-progress").value = event.data; } </script> </head> <body> <div id="result"></div> <progress id="my-progress" value="0" max="100"></progress> </body> </html>
Final effect:
The above is the detailed content of How Spring Boot uses SSE to push data to the front end. For more information, please follow other related articles on the PHP Chinese website!