需求分析
用户在小程序中点击催单按钮后,需要第一时间通知外卖商家
设计思路:*
- 通过WebSocket实现管理端页面和服务端保持长连接状态
- 当用户点击催单按钮后,调用WebSocket的相关API实现服务端向客户端推送消息
- 客户端浏览器解析服务端推送的消息,判断是来单提醒还是客户催单,进行相应的消息提示和语音播报
约定服务端发送给客户端浏览器的数据格式为JSON,字段包括:type,orderId,content- type 为消息类型,1为来单提醒 2为客户催单
- orderId 为订单id
- content 为消息内容
代码开发
Controller层
根据用户催单的接口定义,在user/OrderController中创建催单方法:
/*** 用户催单** @param id* @return*/@GetMapping("/reminder/{id}")@ApiOperation("用户催单")public Result reminder(@PathVariable("id") Long id) {orderService.reminder(id);return Result.success();}
Service层接口
在OrderService接口中声明reminder方法:
/*** 用户催单* @param id*/void reminder(Long id);
Service层实现类
在OrderServiceImpl中实现reminder方法:
/*** 用户催单** @param id*/public void reminder(Long id) {// 查询订单是否存在Orders orders = orderMapper.getById(id);if (orders == null) {throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);}//基于WebSocket实现催单Map map = new HashMap();map.put("type", 2);//2代表用户催单map.put("orderId", id);map.put("content", "订单号:" + orders.getNumber());webSocketServer.sendToAllClient(JSON.toJSONString(map));}
Mapper层
在OrderMapper中添加getById:
/*** 根据id查询订单* @param id*/@Select("select * from orders where id=#{id}")Orders getById(Long id);