文章目录
1、什么是WebSocket?
WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它允许在浏览器和服务器之间进行实时的、双向的通信。相对于传统的基于请求和响应的 HTTP 协议,WebSocket 提供了一种更有效、更实时的通信方式,适用于需要实时更新、实时通知和实时交互的应用。
2、SpringBoot简单调用案例
2.1、SpringBoot引入依赖
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.2、创建实体类
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author chen
* @since 2024-06-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ws_log")
@ApiModel(value = "WsLog对象", description = "")
public class WsLog implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("userid")
private String userId;
@ApiModelProperty("消息")
private String message;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@ApiModelProperty("更改时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
2.3、创建WebSocket保存接口
package com.example.chen.controller;
import com.example.chen.common.infrastructure.common.R;
import com.example.chen.entity.WsLog;
import com.example.chen.service.IWsLogService;
import com.example.chen.websocket.WebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author chen
* @since 2024-06-17
*/
@RestController
@RequestMapping("/chen/wsLog")
@Api(tags = "websocket管理")
public class WsLogController {
@Autowired
public IWsLogService iWsLogService;
@ApiOperation("添加信息")
@PostMapping
public R<String> addSocket(@RequestBody WsLog wsLog){
iWsLogService.save(wsLog);
WebSocket.sendMessage(wsLog.getMessage(),wsLog.getUserId());
return R.success("发送成功");
}
}
2.4、WebSocketConfig配置类
package com.example.chen.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
//开启WebSocket的支持,并把该类注入到spring容器中
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.5、WebSocket类
package com.example.chen.websocket;
import cn.hutool.core.bean.DynaBean;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chen.common.infrastructure.common.R;
import com.example.chen.entity.GoodsType;
import com.example.chen.entity.WsLog;
import com.example.chen.service.IUserService;
import com.example.chen.service.IWsLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocket {
@Autowired
public static IWsLogService iWsLogService;
private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
//实例一个session,这个session是websocket的session
private Session session;
//新增一个方法用于主动向客户端发送消息
public static void sendMessage(Object message, String userId) {
WebSocket webSocket = webSocketMap.get(userId);
Page pageInfo = new Page<>(1, 10);
if (webSocket != null) {
// 构造分页构造器
LambdaQueryWrapper<WsLog> queryWrapper = new LambdaQueryWrapper<>();
// 添加过滤条件
queryWrapper.like(userId != null, WsLog::getUserId, userId);
// 查询
iWsLogService = SpringUtil.getBean(IWsLogService.class);
iWsLogService.page(pageInfo, queryWrapper);
try {
webSocket.session.getBasicRemote().sendText(JSONUtil.toJsonStr(pageInfo));
System.out.println("【websocket消息】发送消息成功,用户="+userId+",消息内容"+message.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static ConcurrentHashMap<String, WebSocket> getWebSocketMap() {
return webSocketMap;
}
public static void setWebSocketMap(ConcurrentHashMap<String, WebSocket> webSocketMap) {
WebSocket.webSocketMap = webSocketMap;
}
//前端请求时一个websocket时
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
webSocketMap.put(userId, this);
sendMessage("CONNECT_SUCCESS", userId);
System.out.println("【websocket消息】有新的连接,连接id"+userId);
}
//前端关闭时一个websocket时
@OnClose
public void onClose(@PathParam("userId") String userId) {
webSocketMap.remove(userId);
System.out.println("【websocket消息】连接断开,总数:"+ webSocketMap.size());
}
//前端向后端发送消息
@OnMessage
public void onMessage(String message,@PathParam("userId") String userId) {
if (!message.equals("ping")) {
System.out.println("【websocket消息】收到客户端发来的消息:"+message);
//保存消息
iWsLogService = SpringUtil.getBean(IWsLogService.class);
iWsLogService.saveMessage(userId, message);
sendMessage(message, userId);
}
}
// @OnMessage
// public void addOnMessage(String message,String userId) {
// if (!message.equals("ping")) {
// System.out.println("接受成功--【websocket消息】收到客户端发来的消息:"+message);
//
// sendMessage(message, userId);
//
// }
// }
}
3、测试效果图
测试连接

使用WebSocket方法

使用接口添加

有多进了一条数据

4、总结
有时候感觉使用使用WebSocket方法去添加数据不是太方便所以就想起来使用接口去添加数据,接口的方法再去调用了WebSocket方WebSocket.sendMessage(wsLog.getMessage(),wsLog.getUserId());然后再去传给前端展示数据。
6816

被折叠的 条评论
为什么被折叠?



