大家好,我是烤鸭:
今天想分享一下springboot+websocket。
之前接到一个需求,需要在页面监听后台的数据(输入邮箱后,需要用户打开邮箱,页面监听用户是否点击激活邮件)。之前的实现方式,是每隔几秒发送ajax请求,根据返回值处理。
后来想试着用websocket实现一下,思路是差不多的。但是方式要简单很多。
环境
springboot 2.1.0.RELEASE
1 项目搭建
简单的springboot项目,需要引入的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<scope>provided</scope>
</dependency>
2 实现思路
当打开页面的时候即和后台建立连接并发送一条消息(唯一key)。这时候用页面的唯一key,每隔一秒缓存(redis)中查询,该key是否存在,存在的话,就说明用户点击了邮件,返回给前台。
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for (WebSocketMonitor item : webSocketSet) {
//找到对应的session发消息
if(item.session.getId().equals(session.getId())){
try {
Timer timer = new Timer();
//每隔一秒查询redis中数据
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(list);
//模拟获取已点击用户
if(redisClient.exists(message)){
try {
sendMessage("i==============="+message);
} catch (IOException e) {
e.printStackTrace();
}finally {
WebSocketMonitor.list.remove(message);
timer.cancel();
}
}
},0,10000);
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3 效果图
4 异常
WebSocket connection to 'ws://localhost:8161/static/webSocketMonitor' failed: Error during WebSocket handshake: Unexpected response code: 404
这种情况是因为springboot的内置容器需要注入ServerEndpointExporter,如果是独立的servlet容器就不需要了。
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocket connection to 'ws://192.168.0.2/static/webSocketMonitor' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
看到有的文章说websoket不支持localhost,改成本机ip后出现这个问题,改成localhost就可以了
5 总结
还是先需求吧,很多都可以实现这种需求,找到最适合的方式。websocket更适合做聊天室这种,毕竟websocket是维持长连接的。可以监听多人连接,将连接广播给连接的各个用户。这些功能在这个需求中有些用不上,所以不是特别适合用。
源码下载:
里边加了list模拟本地触发的情况,redis模拟缓存的情况,用了两个页面用于模拟不同的key,上述的需求是一个页面。
https://download.csdn.net/download/angry_mills/10782754