websocket实现后台像前端主动推送消息的模式,可以减去前端的请求获取数据的模式。而后台主动推送消息一般都是要求消息回馈比较及时,同时减少前端ajax轮询请求,减少资源开销。

spring boot已经集成了websocket,tomcat亦是如此。所以WebSocketConfig配置类就不需要了,不需要开启什么支持,本来就支持。

一、导入依赖

    <!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.5..RELEASE</version>
</dependency>

二、websocket多线程,线上真实环境已经测试过。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; /**
* @Auther: lanhaifeng
* @Date: 2018/11/6 0006 17:59
* @Description: websocket服务端
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @ServerEndpoint 可以把当前类变成websocket服务类
*/
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer { private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class); //存储连接用户的session
private static CopyOnWriteArraySet<String, Session> connections = new CopyOnWriteArraySet<>(); /**
* 打开连接
* @param session
* @param sid
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
connections.put(sid, session);
} /**
* 接收消息
* @param text
*/
@OnMessage
public void onMessage(String text) {
logger.info("收到来新的信息:"+text);
} /**
* 异常处理
* @param throwable
*/
@OnError
public void onError(Throwable throwable) {
throwable.printStackTrace();
} /**
* 关闭连接
* @param sid
*/
@OnClose
public void onClosing(@PathParam("sid") String sid) throws IOException {
connections.remove(sid);
} /**
* 根据IP发送消息
* @param sid
* @param text
*/
public static void sendInfo(String text,@PathParam("sid") String sid) {
try {
Session session = connections.get(sid);
if (session != null && session.isOpen()) {
session.getAsyncRemote().sendText(text);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 遍历群发消息
* @param text
*/
public static void send(String text) {
for (Map.Entry<String, Session> entry : connections.entrySet()) {
sendInfo(text,entry.getKey());
}
} }

在业务中的调用就不介绍了,直接  WebSocketServer.sendInfo(text,sid)

特别注意sendInfo(String message,@PathParam("sid") String sid)两个参数在实际应用中的先后顺序,否则将发送失败。因为找不到该sid的连接。

同时无论是反向代理还是socket本身,60S没有消息会自动断开连接,于是乎

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled; /**
* @Auther: lanhaifeng
* @Date: 2019/5/16 0016 14:29
* @Description:webSocket定时发送消息类
* @statement: 以<60s的频率发送给websocket连接的对象,以防止反向代理的60s超时限制
*/
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class SaticScheduleTask { //3.添加定时任务,55秒是考虑5秒的延迟,从而保证60s的心跳
//@Scheduled(cron = "0/55 * * * * ?")
//或直接指定时间间隔,例如:55秒
@Scheduled(fixedRate=*)
private void configureTasks() throws Exception{
WebSocketServer.send("呼叫动拐,呼叫动拐!");
}
}

spring boot集成Websocket的更多相关文章

  1. spring boot 集成 websocket 实现消息主动推送

    spring boot 集成 websocket 实现消息主动 前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单 ...

  2. Spring Boot 集成 WebSocket 实现服务端推送消息到客户端

    假设有这样一个场景:服务端的资源经常在更新,客户端需要尽量及时地了解到这些更新发生后展示给用户,如果是 HTTP 1.1,通常会开启 ajax 请求询问服务端是否有更新,通过定时器反复轮询服务端响应的 ...

  3. 【websocket】spring boot 集成 websocket 的四种方式

    集成 websocket 的四种方案 1. 原生注解 pom.xml <dependency> <groupId>org.springframework.boot</gr ...

  4. spring boot 集成 websocket 实现消息主动

    来源:https://www.cnblogs.com/leigepython/p/11058902.html pom.xml 1 <?xml version="1.0" en ...

  5. Spring boot集成Websocket,前端监听心跳实现

    第一:引入jar 由于项目是springboot的项目所以我这边简单的应用了springboot自带的socket jar <dependency> <groupId>org. ...

  6. spring boot集成websocket实现聊天功能和监控功能

    本文参考了这位兄台的文章: https://blog.csdn.net/ffj0721/article/details/82630134 项目源码url: https://github.com/zhz ...

  7. Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

    上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...

  8. spring boot集成mybatis-plus插件进行自定义sql方法开发时报nested exception is org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

    spring boot集成mybatis-plus插件进行自定义sql方法开发时报nested exception is org.apache.ibatis.binding.BindingExcept ...

  9. Spring Boot集成Jasypt安全框架

    Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPl ...

随机推荐

  1. 1210 BBS admin后台管理及侧边栏筛选个人站点

    目录 昨日内容 django admin后台管理 使用 建表 用户图片的显示 MEDIA用户配置 查找照片 搭建个人站点 防盗链 新建css文件 侧边栏展示标签 定义分类栏与标签栏 定义时间栏 侧边栏 ...

  2. 0030redis主从复制以及哨兵模式的搭建

    ------------------------------redis主从备份以及哨兵模式------------------------------------------------------- ...

  3. 采集新浪新闻php插件

    今天没事,就分享一个采集新浪新闻PHP插件接口,可用于火车头采集,比较简单,大家可以研究! 新浪新闻实时动态列表为:https://news.sina.com.cn/roll/?qq-pf-to=pc ...

  4. xss获取cookie源码附利用代码

    保存为cookie.asp <% testfile=Server.MapPath("cookies.txt") msg=Request("msg") se ...

  5. 2019-2020-1 20199312 《Linux内核原理与分析》 第八周作业

    ELF(Executable and Linkable Format)可执行的和可链接的格式.(对应Windows为PE) 其包含了以下三类: 可重定位文件:保存着代码和适当的数据,用来和其它的目标文 ...

  6. 自用ajax的json请求

    function singlePriceSubmit(){ var json={}; json["area"]=areaStr1; json["goodCateIdStr ...

  7. HTML5新增input标签属性

    一. input type属性 <form action=""> 邮箱<input type="email" name="" ...

  8. git 查看项目代码统计命令

    git log --author="xxxxxxxx" --pretty=tformat: --numstat | gawk '{ add += $1 ; subs += $2 ; ...

  9. Problem 6 二分

    $des$有 $n$ 个物品,第 $i$ 个物品有两个属性 $k_i, b_i$ ,表示它在时刻 $x$ 的价值为 $k_i \times x + b_i$ .当前处于时刻 $0$ ,你可以选择不超过 ...

  10. 留言板welcome here friends!

    欢迎留言!!! 另附本人信息栏 \(cnblogs\): ShineEternal \(洛谷\):vercont \(CSDN\) \(blog\): ShineEternal \(github\) ...