入门级 Springboot集成websocket通信 ,Scheduled定时推送

2022-08-01,,,,

Spring boot + Websocket + Freemaker
入门级的搭建sprigboot项目,集成freemaker、websocket及相关的配置

1、首先我们创建一个空的maven项目(也可以另一种方式直接初始化一个springboot项目,这里我是maven构建项目,都是可以的)

2、pom.xml修改,引入spring boot、websocket、freemaker

  • 2-1、在dependencies同级引入springboot,父节点定义成springboot,因为项目都是基于springboot开发

     <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.3.1.RELEASE</version>
     </parent>
    
  • 2-2、在 dependencies 下引入 websocket

     <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-websocket</artifactId>
     </dependency>
    
  • 2-3、在 dependencies 下引入freemaker

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    

    2-4、在 dependencies 下引入fastjson,后面json转换需要用到

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.72</version>
    </dependency>
    

3、修改主启动类,加注解@SpringBootApplication,修改main函数

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello websocket
 */
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

4、创建资源文件夹resources

5、这里新建的文件夹还不是项目可识别的资源文件夹,这里需要我们定义一下,选中resources文件,鼠标右击,找到Mark Directory as,再找到Resources Root 点击确认即可。

6、创建配置文件application.yml (当然也可以是application.properties),配置freemaker相关

spring:
  freemarker:
    suffix: .html                                # 设置模板后缀名
    content-type: text/html                      # 设置文档类型
    charset: UTF-8                               # 设置页面编码格式
    cache: false                                 # 设置页面缓存
    template-loader-path: classpath:/templates   # 设置ftl文件路径

7、在resources文件夹下面新建文件夹templates用于存放项目的html页面,这里我们再新建一个index.html,随便写点东西

8、我们再新建一个测试Controller

9、重启项目,访问项目,确认没问题,到这里一个基础的Springboot架构的项目就完成了

10、下面就是我们的重点 websocket,首先添加配置类WebSocketConfig.java

package org.example.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 开启WebSocket支持
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

11、新建WebSocketServer.java

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenjianhua
 * @date 2020/7/13
 */
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {

    /**
     * 线程安全计数器,用来记录当前在线连接数
     */
    private static AtomicInteger count = new AtomicInteger();
    /**
     * ConcurrentHashMap 一个线程安全的支持高并发的HashMap集合类,用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
            //加入set中
        } else {
            webSocketMap.put(userId, this);
            //在线数加1
            count.getAndIncrement();
        }

        log.info("用户连接:" + userId + ",当前在线人数为:" + count.get());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //在线数减1
            count.getAndDecrement();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + count.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (!StringUtils.isEmpty(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId", this.userId);
                String toUserId = jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if (!StringUtils.isEmpty(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                } else {
                    log.error("请求的userId:" + toUserId + "不在该服务器上");
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 发送单个用户自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:" + userId + ",报文:" + message);
        if (!StringUtils.isEmpty(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + ",不在线!");
        }
    }

    /**
     * 给所有用户发送消息
     *
     * @param message
     * @throws IOException
     */
    public static void sendAll(String message) throws IOException {
        for (Map.Entry<String, WebSocketServer> map : webSocketMap.entrySet()) {
            log.info("发送消息:{} 给用户{}", message, map.getKey());
            map.getValue().sendMessage("用户" + map.getKey() + "===" + message);
        }
    }

}



12、改造index.html页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<body>
<div>
    【currentUserId】:
    <input id="userId" name="userId" type="text" value="10">
    <button onclick="openSocket()">开启socket</button>
</div>
<p>
<div>
    【toUserId】:
    <input id="toUserId" name="toUserId" type="text" value="20">
    【content】:
    <input id="contentText" name="contentText" type="text" value="hello websocket">
    <button onclick="sendMessage()">发送消息</button>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;

    function openSocket() {
        if (typeof (WebSocket) == "undefined") {
            alert("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
            var socketUrl = "ws://localhost:8080/websocket/" + $("#userId").val();
            console.log(socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                alert("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function (msg) {
                console.log("接收到信息:" + msg.data);
                alert("接收信息:" + msg.data);
            };
            //关闭事件
            socket.onclose = function () {
                alert("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                alert("websocket发生了错误")
            }
        }
    }

    function sendMessage() {
        if (typeof (WebSocket) == "undefined") {
            alert("您的浏览器不支持WebSocket");
        } else {
            if (socket == null) {
                alert("请开启socket");
                return;
            }
            console.log("您的浏览器支持WebSocket");
            console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
            socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
            alert("消息已发送")
        }
    }
</script>
</html>

13、在TestController.java 添加一个测试方法,发送消息给某个用户

    /**
     * 发送消息给某一个用户
     *
     * @param message
     * @param toUserId
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {
        WebSocketServer.sendInfo(message, toUserId);
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }

14、重启项目,访问 http://localhost:8080

15、开启socket,默认当前用户Id=10,连接成功之后可以看到后台

16、我们可以在开启一个连接,新窗口打开 http://localhost:8080 定义=11,这样的话用户10就可以在线和用户11通信

17、后台定时推送消息给所有在新用户,我们定义一个定时器ScheduleTask.java,定义每10秒发送一条消息给前端用户,重启项目,分别开启用户10,用户11的websocket


import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;

/**
 * @author chenjianhua
 * @date 2020/7/13
 * <p>
 * 定时任务
 */
@Configuration
@EnableScheduling
public class ScheduleTask {

    /**
     * Cron表达式参数分别表示:
     * 秒(0~59) 例如0/5表示每5秒
     * 分(0~59)
     * 时(0~23)
     * 日(0~31)的某天,需计算
     * 月(0~11)
     * 周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
     *
     * @throws IOException
     */
    @Scheduled(cron = "0/10 * * * * ?")
    private void configureTasks() throws IOException {
        WebSocketServer.sendAll("你好!!");
    }
}

后台消息发送日志

前端接收消息日志

如果后台websocket服务停了,前端接收到服务关闭通知

也可以在第三方在线网站 WebSocket在线测试工具 测试websocket连接

OK,到此就整理完了,实现了基础的websocket通讯,后台定时推送消息到前端,具体应用场景和优化根据业务需求再自行优化拓展,看完文章后如有什么见解欢迎多多留言,让我们一起学习,共同进步。。

本文地址:https://blog.csdn.net/qq_36864210/article/details/107324236

《入门级 Springboot集成websocket通信 ,Scheduled定时推送.doc》

下载本文的Word格式文档,以方便收藏与打印。