当前位置: 首页 > ai >正文

苍穹外卖--WebSocket、来单提醒、客户催单

WebSocket

1.介绍

WebSocket是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工通信——浏览器和服务器只需要一次握手,两者之间就可以创建持久性的连接,并进行双向数据传送。

HTTP协议和WebSocket协议对比:

①Http是短连接

②WebSocket是长连接

③Http通信是单向的,基于请求响应模式

④WebSocket支持双向通信

⑤Http和WebSocket底层都是TCP连接

应用场景:

①视频弹幕

②网页聊天

③体育实况更新

④股票基金报价实时更新

效果展示:

2.入门案例

实现步骤:

①直接使用websocket.html页面作为WebSocket客户端

<!DOCTYPE HTML>
<html>
<head><meta charset="UTF-8"><title>WebSocket Demo</title>
</head>
<body><input id="text" type="text" /><button onclick="send()">发送消息</button><button onclick="closeWebSocket()">关闭连接</button><div id="message"></div>
</body>
<script type="text/javascript">var websocket = null;var clientId = Math.random().toString(36).substr(2);//判断当前浏览器是否支持WebSocketif('WebSocket' in window){//连接WebSocket节点websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);}else{alert('Not support websocket')}//连接发生错误的回调方法websocket.onerror = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法websocket.onopen = function(){setMessageInnerHTML("连接成功");}//接收到消息的回调方法websocket.onmessage = function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法websocket.onclose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。window.onbeforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){document.getElementById('message').innerHTML += innerHTML + '<br/>';}//发送消息function send(){var message = document.getElementById('text').value;websocket.send(message);}//关闭连接function closeWebSocket() {websocket.close();}
</script>
</html>

②导入WebSocket的Maven坐标

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

③导入WebSocket服务端组件WebSocketServer,用于和客户端通信

package com.sky.websocket;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.util.Collection;
import java.util.HashMap;
import java.util.Map;/*** WebSocket服务*/
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {//存放会话对象private static Map<String, Session> sessionMap = new HashMap();/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("sid") String sid) {System.out.println("客户端:" + sid + "建立连接");sessionMap.put(sid, session);}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, @PathParam("sid") String sid) {System.out.println("收到来自客户端:" + sid + "的信息:" + message);}/*** 连接关闭调用的方法** @param sid*/@OnClosepublic void onClose(@PathParam("sid") String sid) {System.out.println("连接断开:" + sid);sessionMap.remove(sid);}/*** 群发** @param message*/public void sendToAllClient(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {//服务器向客户端发送消息session.getBasicRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}}

④导入配置类WebSocketConfiguration,注册WebSocket的服务端组件

package com.sky.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** WebSocket配置类,用于注册WebSocket的Bean*/
@Configuration
public class WebSocketConfiguration {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}

⑤导入定时任务类WebSocketTask,定时向客户端推送数据

package com.sky.task;import com.sky.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;@Component
public class WebSocketTask {@Autowiredprivate WebSocketServer webSocketServer;/*** 通过WebSocket每隔5秒向客户端发送消息*/@Scheduled(cron = "0/5 * * * * ?")//这个在后面的代码里还是注释掉好一些,不然语音播报会一直播报public void sendMessageToClient() {webSocketServer.sendToAllClient("这是来自服务端的消息:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));}
}

来单提醒

1.实现思路

用户下单并支付成功后,需要第一时间通知外卖商家。通知的形式有如下两种:

①语音播报

②弹出提示框

设计:

①通过WebSocket实现管理端页面和服务端保持长连接状态

②当客户支付后,调用WebSocket的相关API实现服务端向客户端推送消息

③客户端浏览器解析服务端推送消息,判断是来单提醒还催单,进行相应的消息提示和语音播报

④约定服务端发送给客户端浏览器的数据格式为JSON,字段包括:type,orderId,content

        -type为消息类型,1为来单提醒 2为客户催单

        -orderId为订单id

        -content为消息内容

2.实现代码

在OrderServiceImpl.java中的paySucess方法中添加如下代码:

//通过websocket向客户端浏览器推送消息type orderId contextMap map = new HashMap();map.put("type",1);//1表示来单提醒 2表示客户催单map.put("orderId",ordersDB.getId());map.put("content","订单号:"+outTradeNo);String json = JSON.toJSONString(map);webSocketServer.sendToAllClient(json);

客户催单

1.实现思路

用户在小程序中点击催单按钮后,需要第一时间通知外卖商家。通知的形式有如下两种:

①语音播报

②弹出提示框

设计:

①通过WebSocket实现管理端页面和服务端保持长连接状态

②当客户支付后,调用WebSocket的相关API实现服务端向客户端推送消息

③客户端浏览器解析服务端推送消息,判断是来单提醒还催单,进行相应的消息提示和语音播报

④约定服务端发送给客户端浏览器的数据格式为JSON,字段包括:type,orderId,content

        -type为消息类型,1为来单提醒 2为客户催单

        -orderId为订单id

        -content为消息内容

接口设计:

2.实现代码

OrderController.java代码:

/*** 客户催单* @param id* @return*/@GetMapping("/reminder/{id}")@ApiOperation("客户催单")public Result reminder(@PathVariable("id") Long id){orderService.reminder(id);return Result.success();}

OrderService.java代码:

/*** 客户催单* @param id*/void reminder(Long id);

OrderServiceImpl.java代码:

/*** 客户催单* @param id*/public void reminder(Long id){// 根据id查询订单Orders ordersDB = orderMapper.getById(id);// 校验订单是否存在if (ordersDB == null) {throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);}//通过websocket向客户端浏览器推送消息type orderId contextMap map = new HashMap();map.put("type",2);//1表示来单提醒 2表示客户催单map.put("orderId",id);map.put("content","订单号:"+ordersDB.getNumber());String json = JSON.toJSONString(map);webSocketServer.sendToAllClient(json);}
http://www.xdnf.cn/news/14485.html

相关文章:

  • 【漏洞复现】Apache Kafka Connect 任意文件读取漏洞(CVE-2025-27817)
  • DeepSeek 助力 Vue3 开发:打造丝滑的日历(Calendar),日历_项目里程碑示例(CalendarView01_22)
  • 基于ARM SoC的半导体测试
  • windows,java后端开发常用软件的下载,使用配置
  • python校园拼团系统
  • A 股无风不起浪!金融吸血科技
  • 李宏毅2025《机器学习》第一讲-生成式AI:技术突破和未来发展
  • NAT 与代理服务器 -- NAT,NAPT,正向代理,反向代理
  • RabbitMQ概念
  • 基于python的web系统界面登录
  • P7 QT项目----会学天气预报
  • 黑马python(八)
  • 设置环境变量(linux,windows,windows用指令和用界面)
  • AntV G6入门教程
  • CppCon 2017 学习:C++ in Academia
  • 【开源解析】基于Python+Qt打造智能应用时长统计工具 - 你的数字生活分析师
  • 鼎捷T100开发语言-Genero FGL 终极技术手册
  • Mac OS上安装Redis
  • Python 正则表达式
  • 解决戴尔电脑No bootable devices found问题
  • TIA Portal (博图) 中 SCL 语言 REPEAT_UNTIL循环语句的用法介绍及案例
  • 资源占用多,Linux 系统中如何降低 CPU 资源消耗并提升利用率?
  • CentOS 7 虚拟机网络配置异常 典型问题:启动了NetworkManager但是network无法启动
  • 03.【C语言学习笔记】分支和循环
  • 网络层协议 IP 协议介绍 -- IP 协议,网段划分,私有 IP 和 公网 IP,路由
  • 设计模式笔记_创建型_单例模式
  • 【图像处理入门】9. 基础项目实战:从去噪到图像加密
  • 接口适配器模式实现令牌桶算法和漏桶算法
  • 加密、加签、摘要算法对比
  • 自然语言处理【NLP】—— CBOW模型