9.1 异步请求处理
- Servlet 3开始支持异步请求处理
- Spring MVC 3.2开始支持Servlet3的这项特性
- controller可以从另外一个线程返回一个
java.util.concurrent.Callable
,而不是一个简单的值- 此时Servlet容器线程已经释放,可以处理其他的请求
- Spring MVC通过借助
TaskExecutor
调起另外一个线程(例子中的mvcTaskExecutor
)
- controller也可以从另外一个线程返回一个
DeferredResult
- 此时,Spring MVC并不知道这个线程的存在
- 比如一个定时任务
9.2 演示
-
在
05点睛Spring MVC 4.1-服务器端推送
中,我们也演示了通过SSE实现长连接- 但在IE的一些版本是不支持的
-
本例通过Spring MVC对异步处理的支持来演示长连接的支持,即服务器端推送
- 支持所有浏览器
-
Servlet开启异步支持
package com.wisely;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(DemoMVCConfig.class);
//注册spring mvc的DispatcherServlet
ctx.setServletContext(servletContext);
Dynamic servlet =
servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(true);//此句开启
}
}
-
DeferredResult
所需的定时处理
package com.wisely.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;
@Service
public class AysncService {
private DeferredResult<String> deferredResult;
public DeferredResult<String> getAsyncUpdate() {
deferredResult = new DeferredResult<String>();
return deferredResult;
}
@Scheduled(fixedDelay = 5000)
public void refresh() {
if (deferredResult != null) {
deferredResult.setResult(new Long(System.currentTimeMillis())
.toString());
}
}
}
- 开启Spring MVC支持配置:继承
WebMvcConfigurerAdapter
的配置类DemoMVCConfig
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(30*1000L); //tomcat默认10秒
configurer.setTaskExecutor(mvcTaskExecutor());//所借助的TaskExecutor
}
@Bean
public ThreadPoolTaskExecutor mvcTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setQueueCapacity(100);
executor.setMaxPoolSize(25);
return executor;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/async").setViewName("/async");
}
- 测试控制器
package com.wisely.web;
import java.util.concurrent.Callable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
import com.wisely.service.AysncService;
@Controller
public class AysncController {
@Autowired
AysncService aysncService;
@RequestMapping("/call")
@ResponseBody
public Callable<String> asyncCall() {
//借助mvcTaskExecutor在另外一个线程调用
//此时Servlet容器线程已经释放,可以处理其他的请求
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
return "Async Hello World";
}
};
}
@RequestMapping("/defer")
@ResponseBody
public DeferredResult<String> deferredCall() {
//调用aysncService的getAsyncUpdate方法
//deferredResult被计划任务每五秒钟更新一次
return aysncService.getAsyncUpdate();
}
}
- 测试页面
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="call" onclick="call();"/>
<input type="button" value="deferred" onclick="deferred();"/>
<script type="text/javascript" src="<c:url value="/js/jquery.js" />"></script>
<script type="text/javascript">
function call(){
$.get('call',function(data){
console.log(data);
});
}
function deferred(){
$.get('defer',function(data){
console.log(data);
deferred();//每次请求完成,再发一次请求,避免客户端定时刷新来获取数据
});
}
</script>
</body>
</html>
新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。
京东地址:http://item.jd.com/11894632.html
当当地址:http://product.dangdang.com/23926195.html
亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6
淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail
或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。
相关推荐
4.5.3 服务器端推送技术 106 4.6 Spring MVC 的测试 113 4.6.1 点睛 113 4.6.2 示例 114 第三部分 实战Spring Boot 第5 章 Spring Boot 基础 122 5.1 Spring Boot 概述 122 5.1.1 什么是Spring Boot 122 5.1.2 ...
4.5.3 服务器端推送技术 106 4.6 Spring MVC 的测试 113 4.6.1 点睛 113 4.6.2 示例 114 第三部分 实战Spring Boot 第5 章 Spring Boot 基础 122 5.1 Spring Boot 概述 122 5.1.1 什么是Spring Boot 122 5.1.2 ...
4.5.3 服务器端推送技术 106 4.6 Spring MVC 的测试 113 4.6.1 点睛 113 4.6.2 示例 114 第三部分 实战Spring Boot 第5 章 Spring Boot 基础 122 5.1 Spring Boot 概述 122 5.1.1 什么是Spring Boot 122 5.1.2 ...
点睛网论坛整站源码程序+10W+数据(送主动推送工具) 详细安装教程https://www.songzifc.cn/post/5398.html 原点睛网赚论坛整站源码数据泄漏 效果演示https://www.i6wz.cn/ 【全新优化】点睛网论坛整站程序 带全套...
【全新优化】点睛网论坛整站程序 带全套数据打包(送主动推送工具) 效果演示+详细安装教程https://www.a5ymg.cn/350.html 【全新优化】点睛网论坛整站程序 带全套数据打包(送主动推送工具 首家专用) 带数据打包,...
国元点睛-20230825-国元期货-23页
综合实践-保护眼睛-预防近视-四年级.doc
让消费者眼睛亮起来--稀世宝矿泉水整合营销策划案例(doc 20).doc
这是一款保护眼睛的小软件,绿色软件,不需安装即可使用,试一下吧。
蓝鲸的眼睛读后感-14页.pdf
bugscan发展历程以及框架改进.pdf 基于正则类sql注入防御的绕过技巧.pdf 如何优雅的穿透linux内网.pdf 花式玩转bugscan插件.pdf 过滤型插件与反向代理的火花.pdf
四年级语文下册 6 眼睛 永生的眼睛教案 北师大版-北师大版小学四年级下册语文教案.doc
4.1人的眼睛.pdf
眼睛穴位图-睛明穴-取穴方法 方便经常上网的朋友使用
使用OpenCV1.0实现了眼睛状态识别,首先用harr检测眼睛,然后用模板匹配的方法标记眼睛状态。 程序需要使用Eyes45x11.xml Mouth25x15.xml Nose25x15.xml,将其放到C:\Program Files\OpenCV\data\haarcascades目录下...
图像与眼睛(2009-04-1.pdf
四年级语文下册 6 眼睛 我只看见你的眼睛教案 北师大版-北师大版小学四年级下册语文教案.doc
当我为 API 编写测试并使用 RSpec 进行调试时,我...git checkout -b my-new-feature ) 提交您的更改( git commit -am 'Add some feature' ) 推送到分支( git push origin my-new-feature ) 创建一个新的拉取请求
软件名:点睛文本编码查询 功能:本软件用于将文本的字符串转换为 Text、ASCII、Default、Unicode、BigEndianUnicode、UTF-8、UTF-7、GBK、BIG5 之间的互相转换,用于文本查询。转换结果使用十六进制表示。
基于 swagger 的一些细节不那么让人如意(比如无法处理 map, swagger-ui 中查看响应说明需要切屏, 把脑袋理解成是一台计算机, 眼睛是输入设备, 在看到返回的 json 时, 眼球会自己 parse 成对应的对象, 这时候你还无法...