分享

springBoot 整合websocket

 jackeyqing 2019-04-07

前言:最近开发公司的一个会员卡,酒店预订房间的功能,考虑到要实现后台管理的订单提示,所以在项目中引用websocket,事实上在spring boot中引入webSocket 还是非常简单的,但是我还是爬了很多坑,在此记录一下希望可以帮助一些可能同样会爬坑的同学。

1:jar包的引入,只引这个的前提是使用tomcat7.0以上的版本,我用的是tomcat8,所以用这个就够了,若是低版本的还需引入javaee-api。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

2:配置文件,这里要注意一下,使用springboot的内置tomcat运行和打war包发布到外部Tomcat运行时配置是不一样的。

  1.先创建一个WebSocketConfig.java

   2.使用spring boot内置tomcat运行时的配置。

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. @Component
  5. public class WebSocketConfig {
  6. @Bean
  7. public ServerEndpointExporter serverEndpointExporter(){
  8. return new ServerEndpointExporter();
  9. }
  10. }

 这里的配置是ServerEndpointExporter的注入,配置该出会为我们后面使用到@ServerEndPoint注解的地方自动注册Websocket endpoint。

 3.使用外部的tomcat发布时 WebSocketConfig.java 中就不需要 ServerEndpointExporter 的注入,因为这是它是由外部容器自己提供和管理的,如果你在使用外部容器发布时注入这个bean,项目启动的时候会报 javax.websocket.DeploymentException: Multiple Endpoints may not be deployed to the same path xxxx错误,别问我是怎么知道的(/"≡ _ ≡)/~┴┴。

所以这个时候的配置是这样的:

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. @Component
  5. public class WebSocketConfig {
  6. // @Bean
  7. // public ServerEndpointExporter serverEndpointExporter(){
  8. // return new ServerEndpointExporter();
  9. // }
  10. }

3:上面都配置好后我们就来看websocket使用的重头戏@ServerEndpoint的使用,前面有说。之前的配置就是为了是项目能在使用了注解的地方自动注册Websocket endpoint,在这里我们就能实现websocket的链接、关闭、发送和接收消息的操作,这文件看起来有点像controller,但又有些不同,所以我就把他放在service层了这个有参考慕课网廖师兄的操作。

1.创建一个WebSocket.java。

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.stereotype.Component;
  3. import javax.websocket.OnClose;
  4. import javax.websocket.OnMessage;
  5. import javax.websocket.OnOpen;
  6. import javax.websocket.Session;
  7. import javax.websocket.server.ServerEndpoint;
  8. import java.util.concurrent.CopyOnWriteArraySet;
  9. @Component
  10. @ServerEndpoint(value = "/webSocket")
  11. @Slf4j
  12. public class WebSocket {
  13. private Session session;
  14. private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();
  15. @OnOpen
  16. public void onOpen(Session session){
  17. this.session = session;
  18. webSocketSet.add(this);
  19. log.info("[WebSocket消息]有新的连接,总数:{}", webSocketSet.size());
  20. }
  21. @OnClose
  22. public void onClose(Session session){
  23. webSocketSet.remove(this);
  24. log.info("[WebSocket消息]连接断开,总数:{}", webSocketSet.size());
  25. }
  26. @OnMessage
  27. public void onMessage(String message){
  28. if("123456789".equals(message)){
  29. sendMessage(message);
  30. }
  31. log.info("[WebSocket消息]接收到客户端的消息:{}", message);
  32. }
  33. public void sendMessage(String message){
  34. for (WebSocket webSocket:webSocketSet){
  35. log.info("【websocket消息】广播消息,message=:{}",message );
  36. try {
  37. webSocket.session.getBasicRemote().sendText(message);
  38. }catch (Exception e){
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. }
其实看注解名字也能猜到各个方法的操作的是什么。

@OnOpen:在前端访问websocket时开一个新的连接。这里有用一个集合来记录连接,方便查看管理;

@OnClose:断开连接;

@OnMessage:接收消息接口;

sendMessage:发送消息的接口;

到目前为止服务端的准备就做好了。

现在开始前端调用,这里使用的是原生Html5来调用如下:

  1. <script>
  2. var lockReconnect = false;//避免重复连接
  3. var wsUrl = "ws://localhost:8008/webSocketTest/webSocket";
  4. var ws;
  5. var tt;
  6. createWebSocket();
  7. function createWebSocket() {
  8. try {
  9. ws = new WebSocket(wsUrl);
  10. init();
  11. } catch(e) {
  12. console.log('catch'+e);
  13. reconnect(wsUrl);
  14. }
  15. }
  16. function init() {
  17. ws.onclose = function () {
  18. console.log('链接关闭');
  19. reconnect(wsUrl);
  20. };
  21. ws.onerror = function() {
  22. console.log('发生异常了');
  23. reconnect(wsUrl);
  24. };
  25. ws.onopen = function () {
  26. console.log('建立连接');
  27. //心跳检测重置
  28. heartCheck.start();
  29. };
  30. ws.onmessage = function (event) {
  31. console.log('接收到消息');
  32. if(event.data!="123456789"){
  33. console.log('收到消息:'+event.data);
  34. //弹窗提醒, 播放音乐
  35. $('#myModal').modal('show');
  36. document.getElementById('notice').play();
  37. }
  38. heartCheck.start();
  39. //拿到任何消息都说明当前连接是正常的
  40. }
  41. }
  42. window.onbeforeunload = function () {
  43. ws.close();
  44. }
  45. var lockReconnect = false;//避免重复连接
  46. function reconnect(url) {
  47. if(lockReconnect) {
  48. return;
  49. };
  50. lockReconnect = true;
  51. //没连接上会一直重连,设置延迟避免请求过多
  52. tt && clearTimeout(tt);
  53. tt = setTimeout(function () {
  54. createWebSocket(url);
  55. lockReconnect = false;
  56. }, 4000);
  57. }
  58. //心跳检测
  59. var heartCheck = {
  60. timeout: 60000,
  61. timeoutObj: null,
  62. serverTimeoutObj: null,
  63. start: function(){
  64. console.log('start');
  65. var self = this;
  66. this.timeoutObj && clearTimeout(this.timeoutObj);
  67. this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
  68. this.timeoutObj = setTimeout(function(){
  69. //这里发送一个心跳,后端收到后,返回一个心跳消息,
  70. //onmessage拿到返回的心跳就说明连接正常
  71. console.log('55555');
  72. ws.send("123456789");
  73. self.serverTimeoutObj = setTimeout(function() {
  74. console.log(111);
  75. console.log(ws);
  76. ws.close();
  77. // createWebSocket();
  78. }, self.timeout);
  79. }, this.timeout)
  80. }
  81. }
  82. </script>

其实这里和上面ServerEndpoint一样,想必大家也是见文知意。

无非是初始化一个Websocket,创建连接,关闭连接,接收消息,发送消息,这些就不多说了,主要在这里说一下几个需要注意的点。

1:初始化时 new WebSocket(wsUrl );  这个url就是请求连接@ServerEndpoint配置的地方,所以说它的使用时候是不是有点像Controller的使用,拿上面的请求路径做个说明:

var wsUrl = "ws://localhost:8008/webSocketTest/webSocket";

ws:是websocket的协议,websocket用的不是http协议,这里我就不对这两个协议的区别做详细的说明,有兴趣自己搜一下。需要注意的是如果请求头的是http的就用ws,若请求的是https则使用wss。

localhost:就是服务的ip或域名。

8008:端口号。

webSocketTest:发布的项目名。

webSocket:@ServerEndpoint中配置的路径。

2.websocket长连接有默认的超时时间(proxy_read_timeout),就是超过一定的时间没有发送任何消息,连接会自动断开。所以我们要想保持长连接可以使用心跳包,定时像服务器发送心跳保持通信,上面的js中就有使用,当发生错误或断开连接时我们可以重新连接。

3.最后再提醒一下,如果项目部署到线上是使用了Nginx代理,一定要记得在Nginx配置websocket,前面有说过wesocket使用的不是http协议,如果你用了Nginx又没有配置websocket的话,前端初始化websocket就会报404。

下面引用其他博主的一个解决方案,具体参考:springboot + websocket + linux服务器(nginx)404问题解决

配置nginx反向代理响应webSocket请求 需要在代理的请求配置中加入下面的配置:

  1. proxy_set_header Upgrade $http_upgrade;
  2. proxy_set_header Connection "upgrade";1

 Nginx配置

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. #charset koi8-r;
  5. location / {
  6. root /usr/java/myproject/sell;
  7. index index.html index.htm;
  8. }
  9. location /sell/ {
  10. proxy_pass http://127.0.0.1:8081/sell/;
  11. }
  12. location /sell/webSocket {
  13. proxy_pass http://127.0.0.1:8081/sell/webSocket;
  14. proxy_set_header Upgrade $http_upgrade;
  15. proxy_set_header Connection "upgrade";
  16. }
 
 

 

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多