1.websocket介绍
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。
1.websocket2应用
(1)系统实时通告
(2)即时聊天
(3)弹幕
(4)实时数据更新:比如体育实况更新、股票基金报价实时更新
(5)代替轮询,提高效率。
本案例为有人下单之后先客户端推送消息
第一步引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二步添加配置类
@Component
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
第三步:编写连接代码
@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
public Session session;
//存储连接信息
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("打开链接");
webSockets.add(this);
}
@OnClose
public void onClose() {
System.out.println("关闭连接");
webSockets.remove(this);
}
@OnMessage
public void onMessage(String message) {
System.out.println("收到客户端发来的消息" + message);
}
//向客户端发送消息的方法
public void sendMessage(String message) {
for (WebSocket webSocket : webSockets) {
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
第四步:编写下单接口
//注入第三步的WebSocket类
@Autowired
private WebSocket webSocket;;
@AppLog(value = "订单支付", type = 1)
@AuthCheck
@PostMapping("/order/pay")
@ApiOperation(value = "订单支付", notes = "订单支付")
public ApiResult<T> confirm(@Validated @RequestBody PayParam param) {
//订单支付的业务逻辑
........
//向前端推送消息
String message="用户XXX下单";
webSocket.sendMessage(message);
return ApiResult.ok();
}
测试(webSocket客户端网址)
https://websocket.jsonin.com/
至此 完成消息推送。由于我加了配置(server.servlet.context-path: /api) 所以有/api 大家没有 的可以不加。
希望对大家有帮助。