spring boot集成Websocket
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的更多相关文章
- spring boot 集成 websocket 实现消息主动推送
spring boot 集成 websocket 实现消息主动 前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单 ...
- Spring Boot 集成 WebSocket 实现服务端推送消息到客户端
假设有这样一个场景:服务端的资源经常在更新,客户端需要尽量及时地了解到这些更新发生后展示给用户,如果是 HTTP 1.1,通常会开启 ajax 请求询问服务端是否有更新,通过定时器反复轮询服务端响应的 ...
- 【websocket】spring boot 集成 websocket 的四种方式
集成 websocket 的四种方案 1. 原生注解 pom.xml <dependency> <groupId>org.springframework.boot</gr ...
- spring boot 集成 websocket 实现消息主动
来源:https://www.cnblogs.com/leigepython/p/11058902.html pom.xml 1 <?xml version="1.0" en ...
- Spring boot集成Websocket,前端监听心跳实现
第一:引入jar 由于项目是springboot的项目所以我这边简单的应用了springboot自带的socket jar <dependency> <groupId>org. ...
- spring boot集成websocket实现聊天功能和监控功能
本文参考了这位兄台的文章: https://blog.csdn.net/ffj0721/article/details/82630134 项目源码url: https://github.com/zhz ...
- Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件
上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...
- 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 ...
- Spring Boot集成Jasypt安全框架
Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPl ...
随机推荐
- LGOJ P2048 [NOI2010]超级钢琴
题目描述 小Z是一个小有名气的钢琴家,最近C博士送给了小Z一架超级钢琴,小Z希望能够用这架钢琴创作出世界上最美妙的音乐. 这架超级钢琴可以弹奏出n个音符,编号为1至n.第i个音符的美妙度为Ai,其中A ...
- 移动端跨平台应用开发(ios、Android、web)- Flutter 技术
关键词:Google 出品:Dart语言:Flutter Engine引擎:响应式设计模式:原生渲染:免费并且开源 一.简介 Flutter 是谷歌2018年发布的跨平台移动UI框架.作为谷歌的开源移 ...
- 【EF】vs2017中没有EF模型
在添加->新建项目 中找不到实体模型? 或者 在vs中打开edmx文件时,显示的只有文本,没有图形模式 原因:是因为没有安装实体模型插件 解决方法: 1.打开网址 https://marketp ...
- PHP获取POST数据的三种方式
一.PHP获取POST数据的几种方法 方法1.最常见的方法是:$_POST['fieldname']; 说明:只能接收Content-Type: application/x-www-form-urle ...
- Bzoj 1010: [HNOI2008]玩具装箱toy(斜率优化)
1010: [HNOI2008]玩具装箱toy Time Limit: 1 Sec Memory Limit: 162 MB Description P教授要去看奥运,但是他舍不下他的玩具,于是他决定 ...
- Pytest权威教程07-Monkeypatching,对模块和环境进行Mock
目录 Monkeypatching,对模块和环境进行Mock 简单示例如: 猴子补丁方法 Monkeypatching 返回对象: 构建mock类 全局补丁示例如:阻止"requests&q ...
- [CTF]抓住那只猫(XCTF 4th-WHCTF-2017)
原作者:darkless 题目描述:抓住那只猫 思路: 打开页面,有个输入框输入域名,输入baidu.com进行测试 发现无任何回显,输入127.0.0.1进行测试. 发现已经执行成功,执行的是一个p ...
- leetcode 467. 环绕字符串中唯一的子字符串
题目描述: 把字符串 s 看作是“abcdefghijklmnopqrstuvwxyz”的无限环绕字符串,所以 s 看起来是这样的:"...zabcdefghijklmnopqrstuvwx ...
- Windows下基于IIS服务的SSL服务器的配置
Windows下基于IIS服务的SSL服务器的配置 实验环境 Windows Server 2008 R1(CA) Windows Server 2008 R2(web服务器) Windows 7 x ...
- java 跳出多重循环
public class Main { public static void main(String[] args) { System.out.println("start"); ...