09点睛Spring MVC4.1-异步请求处理(包含兼容浏览器的服务器端推送)
转发地址:https://www.iteye.com/blog/wiselyman-2215852
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>
测试
- 访问http://localhost:8080/testSpringMVC/async
- 点击call
- 点击defer
09点睛Spring MVC4.1-异步请求处理(包含兼容浏览器的服务器端推送)的更多相关文章
- 08点睛Spring MVC4.1-Spring MVC的配置(含自定义HttpMessageConverter)
8.1 配置 Spring MVC的配置是通过继承WebMvcConfigurerAdapter类并重载其方法实现的; 前几个教程已做了得配置包括 01点睛Spring MVC 4.1-搭建环境 配置 ...
- 07点睛Spring MVC4.1-ContentNegotiatingViewResolver
转发地址:https://www.iteye.com/blog/wiselyman-2214965 7.1 ContentNegotiatingViewResolver ContentNegotiat ...
- 10点睛Spring MVC4.1-全局异常处理
10.1 全局异常处理 使用@ControllerAdvice注解来实现全局异常处理; 使用@ControllerAdvice的属性缩小处理范围 10.2 演示 演示控制器 package com.w ...
- Spring Web Async异步处理#Callable #DeferredResult
Spring MVC 对于异步请求处理的两种方式 场景: Tomcat对于主线程性能瓶颈,当Tomcat请求并发数过多时,当线程数满时,就会出现请求等待Tomcat处理,这个时候可以使用子线程处理业务 ...
- 使用AJAX技术发送异步请求,HTTP服务端推送
使用AJAX技术发送异步请求 什么是AJAX AJAX指一步Javascript和XML(Asynchronous JavaScript And XML),它是一些列技术的组合,简单来说AJAX基于X ...
- MVC异步消息推送机制
在MVC里面,有异步控制器,可以实现模拟消息推送机制功能 1.控制器要继承至AsyncController,如 public class RealTimeController : AsyncContr ...
- Spring Mvc4 新特性(一)
前言 Spring Framework的Web层,由spring-web,spring-webmvc,spring-websocket和spring-webmvc-portlet模块组成. 很多人刚学 ...
- 高性能的关键:Spring MVC的异步模式
我承认有些标题党了,不过话说这样其实也没错,关于“异步”处理的文章已经不少,代码例子也能找到很多,但我还是打算发表这篇我写了好长一段时间,却一直没发表的文章,以一个更简单的视角,把异步模式讲清楚. 什 ...
- Spring MVC的异步模式
高性能的关键:Spring MVC的异步模式 我承认有些标题党了,不过话说这样其实也没错,关于“异步”处理的文章已经不少,代码例子也能找到很多,但我还是打算发表这篇我写了好长一段时间,却一直没发表 ...
随机推荐
- [LuoguP1462]通往奥格瑞玛的道路
题目链接 题意简述:现在有一个图,每经过一个点就会交钱,走一条路就会扣血.在血量>0的前提下,要从1走到n点,并且要求路径上交钱的最大值最小. 解题思路:首先最大值最小,我们选择二分.目前有两个 ...
- mage Ansible学习2 Playbook
一.上集回顾 1.运维: 手动 --> 标准化 --> 工具化 --> 自动化 --> 智能化 2.工具化 OS Install:PXE ,Cobbler:Virutaliza ...
- iframe标签在PC端的使用
随着前端框架的崛起 各种组件化 模块化开发 然而我发现在PC端要考虑兼容 ~~~~ 自己琢磨着 在PC端怎么吧一个页面做成一个公共的部分 发现有个iframe标签可以在页面中嵌套 虽然iframe可 ...
- 36、将RDD转换为DataFrame
一.概述 为什么要将RDD转换为DataFrame? 因为这样的话,我们就可以直接针对HDFS等任何可以构建为RDD的数据,使用Spark SQL进行SQL查询了.这个功能是无比强大的. 想象一下,针 ...
- Error instantiating class cn.edu.zju.springmvc.pojo.Items with invalid types () or values (). 报错解决方法
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.Reflecti ...
- CF1187F Expected Square Beauty(期望)
题目 CF1187F Expected Square Beauty 做法 \(B(x)=\sum\limits_{i=1}^n I_i(x),I_i(x)=\begin{cases}1&x_i ...
- Parse发布Bolts,一个面向iOS和Android的底层库集合
转载自:http://www.infoq.com/cn/news/2014/02/parse-announces-bolts 数月前,Parse被Facebook收购.最近,它开源了一个面向iOS和A ...
- Django框架,python2和python3共存的情况下,创建Django项目
一.python2和python3共存的情况下,直接使用 django-admin startproject Django-project 这个时候系统默认使用的是python2创建,可能由于pyth ...
- #软件更新#Visual Studio更新到16.3.8
#软件更新#Visual Studio更新到16.3.8 此次更新包括以下内容:(1)支持Xcode 11.2.(2)修复无法从System.String类型转化的bug.(3)修复UWP开发中,加载 ...
- System.Net.FtpWebRequest.cs
ylbtech-System.Net.FtpWebRequest.cs 实现文件传输协议(FTP)客户端. 1.返回顶部 1. #region 程序集 System, Version=4.0.0.0, ...