一、根据业务需求,需要写一个实时订单的接口,
使用spring的DeferedResult进行异步推送消息到客户端
当浏览器发送请求到服务端时,请求到服务端,服务端捕获请求。待定时器更新后,再返回数据到页面
二、具体操作步骤:
1、定义Conroller类
package dcc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import dcc.service.PushService;
@RestController
@RequestMapping("/timeorder")
public class TimeOrderController {
@Autowired
private PushService pushService;
/**
* 门店地图实时订单
* @return
*/
@PostMapping("/selectTimeOrder")
public DeferredResult<String> selectTimeOrder() {
return pushService.getAsyncUpdate();
}
}
2、定义service类
package dcc.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;
@Service
public class PushService {
private DeferredResult<String> deferredResult;
public DeferredResult<String> getAsyncUpdate(){
deferredResult = new DeferredResult<String>();
return deferredResult;
}
/**
* 10秒更新一次
*/
@Scheduled(fixedDelay = 10000)
public void refreshOrder() {
if(deferredResult!=null){
//这里返回时间戳,可根据实际情况,查询数据库,返回对呀的数据
deferredResult.setResult(new Long(System.currentTimeMillis()).toString());
}
}
}
3、spring配置文件,添加task,让@Scheduled生效
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<!-- 定时器开关 -->
<task:annotation-driven />
spring配置文件中,多余的配置,没有添加,结合实际项目添加
4、配置web.xml,开启异步
<async-supported>true</async-supported>
涉及到这个controller的每一个serlvet都要添加上,截图如下
5、编写ajax代码
//获取服务端推送信息demo
function getTimeOrder(){
$.ajax({
url:"http://localhost:8080/dcc/timeorder/selectTimeOrder",
method:"post",
success:function(data){
console.log(data);
getTimeOrder();
}
});
}
getTimeOrder();
6、启动项目,效果图: