springboog+websocket

294 篇文章 13 订阅

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页面的目的,效果如下图

关键词相关技术,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/

scok.js客户端:https://github.com/sockjs/sockjs-client

spring webSocket:https://docs.spring.io/spring/docs/

https://cloud.tencent.com/developer/article/1096792

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值