springboog+websocket 朱雀 2021-05-12 11:49 403阅读 0赞 JavaEE 7中出了JSR-356:Java API for WebSocket规范;不少Web容器,如Tomcat,Nginx,Jetty等都支持WebSocket;同时绝大多数浏览器也支持webSocket。 接下来我们使用springboot来搭建一个websocket服务器部署到tomcat中,前端使用websocket的js库实现二者通讯。 需求:实时将系统日志输出的前端web页面,因为是实时输出,所有第一时间就想到了使用webSocket。而且在spring boot中,使用websocket超级方便。本文使用到的技术包括:spring boot自带的webSocket模块提供stomp的服务端,前端使用stomp.min.js做stomp的客户端,使用sockjs来链接。前端订阅后端日志端点的消息,后端实时推送,达到日志实时输出到web页面的目的,效果如下图 ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdXhpYW83MjM4NDY_size_16_color_FFFFFF_t_70][] 关键词相关技术,WebSocket(stopmp服务端),stomp协议,sockjs.min.js,stomp.min.js(stomp客户端), **首先了解下stomp:** STOMP即Simple (or Streaming) Text Orientated Messaging Protocol,简单(流)文本定向消息协议,它提供了一个可互操作的连接格式,允许STOMP客户端与任意STOMP消息代理(Broker)进行交互。STOMP协议由于设计简单,易于开发客户端,因此在多种语言和多种平台上得到广泛地应用。 STOMP协议的前身是TTMP协议(一个简单的基于文本的协议),专为消息中间件设计。 STOMP是一个非常简单和容易实现的协议,其设计灵感源自于HTTP的简单性。尽管STOMP协议在服务器端的实现可能有一定的难度,但客户端的实现却很容易。例如,可以使用Telnet登录到任何的STOMP代理,并与STOMP代理进行交互。 **代码:** 1)pom.xml:springboot websocket依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> 2)配置WebSocket消息代理端点,即stomp服务端: @Configuration public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/websocket") //.setAllowedOrigins("http://localhost:8976") .withSockJS(); } } 3)启动类,开启webSocket消息代理功能,并推送日志信息: @SpringBootApplication @EnableWebSocketMessageBroker public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } @Autowired private SimpMessagingTemplate messagingTemplate; @PostConstruct public void pushLogger(){ ExecutorService executorService=Executors.newFixedThreadPool(2); Runnable runnable=new Runnable() { @Override public void run() { while (true) { try { JSONObject log = new JSONObject(); log.put("time", new Date().getTime()); log.put("name", Thread.currentThread().getName()); if(log!=null){ if(messagingTemplate!=null) messagingTemplate.convertAndSend("/topic/pullLogger",log); } } catch (Exception e) { e.printStackTrace(); } } } }; executorService.submit(runnable); executorService.submit(runnable); } } 通过SimpMessagingTemplate类推送数据。 4)前端页面: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>WebSocket Logger</title> <script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script> <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script> <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script> </head> <body> <button onclick="openSocket()">开启日志</button><button onclick="closeSocket()">关闭日志</button> <div id="log-container" style="height: 450px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;"> <div></div> </div> </body> <script> var stompClient = null; $(document).ready(function() {openSocket();}); function openSocket() { if(stompClient==null){ var socket = new SockJS('http://localhost:8080/websocket?token=kl'); stompClient = Stomp.over(socket); stompClient.connect({token:"kl"}, function(frame) { stompClient.subscribe('/topic/pullLogger', function(event) { var content=JSON.parse(event.body); $("#log-container div").append(content.timestamp +" "+ content.level+" --- ["+ content.threadName+"] "+ content.className+" :"+content.body).append("<br/>"); $("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height()); },{ token:"kltoen" }); }); } } function closeSocket() { if (stompClient != null) { stompClient.disconnect(); stompClient=null; } } </script> </body> </html> 前端通过http方式访问tomcat的8080端口,并且指定springboot配置的代理节点/websocket,即可访问到websocket。(var socket = new SockJS('http://localhost:8080/websocket?token=kl');) **参考地址:** stomp.js客户端:[http://jmesnil.net/stomp-websocket/doc/][http_jmesnil.net_stomp-websocket_doc] scok.js客户端:[https://github.com/sockjs/sockjs-client][https_github.com_sockjs_sockjs-client] spring webSocket:[https://docs.spring.io/spring/docs/][https_docs.spring.io_spring_docs] [https://cloud.tencent.com/developer/article/1096792][https_cloud.tencent.com_developer_article_1096792] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdXhpYW83MjM4NDY_size_16_color_FFFFFF_t_70]: /images/20210511/f774562b4b654d809e8b0445b5dc64bd.png [http_jmesnil.net_stomp-websocket_doc]: http://jmesnil.net/stomp-websocket/doc/ [https_github.com_sockjs_sockjs-client]: https://github.com/sockjs/sockjs-client [https_docs.spring.io_spring_docs]: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket [https_cloud.tencent.com_developer_article_1096792]: https://cloud.tencent.com/developer/article/1096792
还没有评论,来说两句吧...