课程内容
- Spring Task
- 订单状态定时处理
- WebSocket
- 来电提醒
- 客户催单
Spring Task
- Spirng框架提供的任务调动工具
- 可以按照约定的时间自动执行某个代码逻辑
- 定位: 定时任务框架
- 作用:定时自动执行某段java代码
- 应用场景
- 银行卡每月还款提醒
- 火车售票系统处理未支付订单
- 纪念日发送通知
Cron表达式
- 本质上是字符串
- 通过cron表达式可以定义任务触发的时间
- 构成规则: 分为6或7个域 由空格分隔开 每个域代表一个含义
- 每个域的含义分别为 秒 分钟 小时 日 月 周 年
- 一半日和周不同时设置 其中一个设置另一个用?表示
- 一半我们不手动写cron表达式 可通过一些在线生成器实现
通配符
*
表示所有值
?
表示未说明的值 即不关心它为和值
-
表示一个指定的范围
,
表示一个指定的可能值
/
符号签表示开始时间 , 符号后表示每次递增的值
使用步骤
- 导入maven坐标(已存在)
- 启动类添加注解@EnableScheduling 开启任务调度
- 自定义定时任务咧
代码开发
//自定义定时任务类
@Compoent
@Slf4j
public class MyTask{
//定时任务 每隔五秒触发一次
@Scheduled(cron = "0/5 * * * * ?")
public void executeTask(){
log,info("定时任务开始执行:{}",new Date());
}
}
- 开启任务调度
- 启动类添加注解@EnableScheduling
订单状态定时处理
- 通过定时任务每分钟检查一次是否存在支付超时订单
- 下单后超过15分钟仍未支付判定为支付超时订单
- 如果存在则修改订单状态的已取消
- 通过定时任务每天凌晨一点检查一次是否存在"派送中"的订单
- 如果存在则修改订单状态为"已完成"
代码开发
@Component
@Slf4j
public class OrderTask {
@Autowired
private OrderMapper orderMapper;
/**
* 处理支付超时订单
*/
@Scheduled(cron = "0 * * * * ?")
public void processTimeoutOrder(){
log.info("处理支付超时订单:{}", new Date());
}
/**
* 处理“派送中”状态的订单
*/
@Scheduled(cron = "0 0 1 * * ?")
public void processDeliveryOrder(){
log.info("处理派送中订单:{}", new Date());
}
}
@Select("select * from orders where status = #{status} and order_time < #{orderTime}")
List<Orders> getByStatusAndOrdertimeLT(Integer status, LocalDateTime orderTime);
- 完善定时任务类的processTimeoutOrder方法
//处理支付超时订单
@Scheduled(cron = " 0 * * * * ?")
public void processTimeoutOrder(){
log.info("处理支付超时订单;{}",new Date());
LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
//当前时间-15分钟
List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
if (orderList != null && !orderList.isEmpty()) {
orderList.forEach(order -> {
order.setStatus(Orders.CANCELLED);
order.setCancelReason("支付超时,自动取消");
order.setCancelTime(LocalDateTime.now());
orderMapper.update(order);
});
}
}
//处理"派送中"的订单
@Scheduled(cron = "0 0 1 * * ?")
public void processDeliveryOrder() {
log.info("处理派送中订单;{}", new Date());
LocalDateTime time = LocalDateTime.now().plusHours(-1);
//当前时间-1小时
List<Orders> orderList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
if (orderList != null && !orderList.isEmpty()) {
orderList.forEach(order -> {
order.setStatus(Orders.COMPLETED);
orderMapper.update(order);
});
}
}
WebSocket
介绍
- 基于tcp的一种新的网络协议
- 实现了浏览器和服务器的全双工通信–
- 浏览器和服务器只需要一次握手
- 就可以完成持久性的连接 并进行双向数据传输
- 与http的对比
- http是短连接 WebSocket是长连接
- http通信基于请求响应 单方面
- WebsSocket支持双向通信
- HTTP和WebSocket底层都是TCP连接
- 应用场景
- 视频弹幕
- 网页聊天
- 体育实况更新
- 股票基金报价实时更新
入门案例
- 实现浏览器与服务器全双工通信。
- 浏览器既可以向服务器发送消息
- 服务器也可主动向浏览器推送消息。
实现步骤
- 直接使用websocket.html页面作为WebSocket客户端
- 导入WebSocket的maven坐标
- 导入WebSocket服务端组件WebSocketServer 用于和客户端通信
- 导入配置类WebSocketConfiguration 注册WebSocket的服务端组件
- 导入定时任务类Websocket
代码开发
- 定义websocket.html页面(资料中已提供)
<!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);
//判断当前浏览器是否支持WebSocket
if('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>
- 导入maven坐标
- 在sky-server模块pom.xml已定义
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 定义WebSocket服务端组件
- 直接导入到sky-server模块
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {
//存放会话对象
private static Map<String, Session> sessionMap = new HashMap();
//连接建立成功调用的方法
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
System.out.println("客户端:" + sid + "建立连接");
sessionMap.put(sid, session);
}
//收到客户端消息后调用的方法
ssage
public void onMessage(String message, @PathParam("sid") String sid) {
System.out.println("收到来自客户端:" + sid + "的信息:" + message);
}
//连接关闭调用的方法
public void onClose(@PathParam("sid") String sid) {
System.out.println("连接断开:" + sid);
sessionMap.remove(sid);
}
//群发
public void sendToAllClient(String message) {
Collection<Session> sessions = sessionMap.values();
for (Session session : sessions) {
try {
//服务器向客户端发送消息
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 定义配置类 注册WebSocket的服务端组件
- 从资料总直接导入
@Configuration
public class WebSocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 定义定时任务类 定时向客户端推送数据
- 从资料中直接导入即可
@Component
public class WebSocketTask {
@Autowired
private WebSocketServer webSocketServer;
/**
* 通过WebSocket每隔5秒向客户端发送消息
*/
@Scheduled(cron = "0/5 * * * * ?")
public void sendMessageToClient() {
webSocketServer.sendToAllClient("这是来自服务端的消息:" + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
}
}
来单提醒
设计思路
- 通过WebSocket实现管理端页面和服务端保持长连接状态
- 当客户支付后 调用WebSocket的相关API实现服务端向客户端推送消息
- 客户端浏览器解析服务端而推送的消息 判断是来单提醒还是客户催单
- 进行相应的消息提示和语音不报
- 约定服务端发送给客户端浏览器的数据格式为JSON
- 字段包括: type orderld content
- type为消息类型 1为来电提醒 2 为客户催单
- orderld为订单id
- content为消息内容
代码开发
- 在OrderServiceImpl中注入WebSocketServer方法
- 修改paySuccess方法 加入如下代码
//支付成功后,服务端通过WebSocket推送消息给客户端
Map map = new HashMap();
map.put("type",1);//消息类型 1表示来单提醒
map.put("orderId",ordersDB.getId());
map.put("content","订单号" + outTradeNo);
//通过WebSocket实现来单提醒,向客户端浏览器推送消息
webSocketServer.sendToAllClient(JSON.toJSONString(map));
客户催单
设计思路
代码开发
Controller层
- 在user/OrderCController中创建催单方法
//用户催单
@GetMapping("reminder/{id}")
@ApiOperation("用户催单")
public Result reminder(@PathVariable("id") Long id){
orderService.reminder(id);
return Result.success();
}
Service层
- 在OrderService中声明reminder方法
//订单催单
void reminder(Long id);
public void reminder(Long id) {
// 根据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));
}