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

1 篇文章 0 订阅
1 篇文章 0 订阅

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通讯,后台定时推送消息到前端,具体应用场景和优化根据业务需求再自行优化拓展,看完文章后如有什么见解欢迎多多留言,让我们一起学习,共同进步。。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Boot集成WebSocket实现消息推送,需要进行以下步骤: 1. 添加Spring Boot WebSocket依赖 2. 创建WebSocket配置类 3. 创建WebSocket处理器类 4. 创建WebSocket拦截器类 5. 创建WebSocket消息模型类 6. 在Spring Boot中使用WebSocket 下面是一个简单的示例代码: 1. 添加Spring Boot WebSocket依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类 创建一个WebSocket配置类,用于配置WebSocket相关的参数,如下所示: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new WebSocketHandler(), "/websocket").addInterceptors(new WebSocketInterceptor()); } } ``` 3. 创建WebSocket处理器类 创建一个WebSocket处理器类,用于处理WebSocket连接、断开连接和接收消息等操作,如下所示: ``` public class WebSocketHandler extends TextWebSocketHandler { private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession s : sessions) { s.sendMessage(message); } } } ``` 4. 创建WebSocket拦截器类 创建一个WebSocket拦截器类,用于拦截WebSocket连接请求,如下所示: ``` public class WebSocketInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } } ``` 5. 创建WebSocket消息模型类 创建一个WebSocket消息模型类,用于封装WebSocket消息,如下所示: ``` public class WebSocketMessage { private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } } ``` 6. 在Spring Boot中使用WebSocket 在Spring Boot中使用WebSocket非常简单,只需要在Controller中注入WebSocketSession即可,如下所示: ``` @Controller public class WebSocketController { @Autowired private WebSocketSession session; @MessageMapping("/send") public void send(WebSocketMessage message) throws Exception { session.sendMessage(new TextMessage(message.getContent())); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值