如何实现web请求的异步处理

简介: 如何实现web请求的异步处理

正文


目前,我们编写的代码基本上都是同步请求的,我们每次请求,都会占用过客户端的一个资源,一个链接,导致连接数减少。如何进行异步处理,那么我们处理的速度会大大的增加。


方法一:servlet3.0后,我们的servlet支持了异步请求的方式来执行我们的业务逻辑。


通过request.startAsync(request, response)来将同步请求转为异步,该方法返回一个AsyncContext 对象,在A中将该对象保存起来,等B的响应到来的时候,就可以利用该对象来拿到response,向A反馈响应了

xml配置:<async-supported>true</async-supported>

注解配置:@WebServlet(urlPatterns = { "/app/*" }, asyncSupported = true)


异步请求的过程:

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request=(HttpServletRequest)req;
    final HttpServletResponse response=(HttpServletResponse)res;
    AsyncContext asyncContext = request.getAsyncContext();
   // 开启另一个线程
    asyncContext.start(new Runnable() {
        @Override
        public void run() {
            try {
                 // 返回数据
                response.getWriter().print("执行成功");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}


方法二:Spring-mvc的方式


在我们Spring的官方文档中,我们可以知道,Spring对于一步的请求也是支持的,文档地址:

https://docs.spring.io/spring/docs/5.2.8.BUILD-SNAPSHOT/spring-framework-reference/web.html#mvc-ann-async

Spring MVC has an extensive integration with Servlet 3.0 asynchronous request processing:

  • DeferredResult and Callable return values in controller methods and provide basic support for a single asynchronous return value.
  • Controllers can stream multiple values, including SSE and raw data.
  • Controllers can use reactive clients and return reactive types for response handling.

要想实现,异步请求,我们要在基本的servlet上面配置支持异步请求:

In web.xml configuration, you can add <async-supported>true</async-supported> to the DispatcherServlet and to Filter declarations and add <dispatcher>ASYNC</dispatcher> to filter mappings.

下面介绍2种最常用的:

  1. 使用 DeferredResult 来完成异步请求:
@GetMapping("/quotes")
@ResponseBody
public DeferredResult<String> quotes() {
       DeferredResult<String> deferredResult = new DeferredResult<String>();
       // Save the deferredResult somewhere..
       return deferredResult;
}
    // From some other thread...
    deferredResult.setResult(result);

从上面我们可以知道:处理请求的是一个线程,业务逻辑是另一个线程。


  1. 使用Callable 来完成异步请求:


@PostMapping
public Callable<String> processUpload(final MultipartFile file) {
   return new Callable<String>() {
       public String call() throws Exception {
           // ...
           return "someView";
      }
  };
}

这样我们就可以实现请求的异步请求。

相关文章
|
10月前
|
存储 开发框架 JSON
在 Python 中,如何处理 Web 请求和响应?
【2月更文挑战第26天】【2月更文挑战第90篇】在 Python 中,如何处理 Web 请求和响应?
206 0
[Web程序设计]实验: 请求与响应
[Web程序设计]实验: 请求与响应
139 0
|
2月前
|
安全 Java 数据安全/隐私保护
springSecurity学习之springSecurity过滤web请求
通过配置 Spring Security 的过滤器链,开发者可以灵活地管理 Web 请求的安全性。理解核心过滤器的作用以及如何配置和组合这些过滤器,可以帮助开发者实现复杂的安全需求。通过具体的示例代码,可以清晰地了解 Spring Security 的配置方法和实践。
76 23
|
7月前
|
开发框架 缓存 .NET
并发请求太多,服务器崩溃了?试试使用 ASP.NET Core Web API 操作筛选器对请求进行限流
并发请求太多,服务器崩溃了?试试使用 ASP.NET Core Web API 操作筛选器对请求进行限流
284 0
|
6月前
|
SQL 存储 安全
Web安全-CSRF跨站请求伪造
Web安全-CSRF跨站请求伪造
141 4
|
10月前
|
前端开发 数据库 Python
使用 Python 的 Web 框架(如 Django 或 Flask)来建立后端接口,用于处理用户的请求,从数据库中查找答案并返回给前端界面
【1月更文挑战第13天】使用 Python 的 Web 框架(如 Django 或 Flask)来建立后端接口,用于处理用户的请求,从数据库中查找答案并返回给前端界面
293 7
|
7月前
|
存储 测试技术 开发者
FastAPI异步处理的神奇之处:如何用Python打造高性能Web应用,让你的项目一鸣惊人?
【8月更文挑战第31天】在现代Web开发中,高性能至关重要。FastAPI作为一款高性能Python Web框架,支持多种异步处理方式,包括非阻塞I/O、异步函数(async/await)及异步上下文管理器(async with),能够大幅提升应用性能。本文通过示例代码详细介绍了FastAPI中的异步处理方法,并分享了最佳实践,帮助开发者构建高效的Web应用。
286 0
|
7月前
|
Web App开发 安全 JavaScript
【Azure 应用服务】App Service 通过配置web.config来添加请求返回的响应头(Response Header)
【Azure 应用服务】App Service 通过配置web.config来添加请求返回的响应头(Response Header)
113 0
|
7月前
|
API
【Azure API 管理】在 Azure API 管理中使用 OAuth 2.0 授权和 Azure AD 保护 Web API 后端,在请求中携带Token访问后报401的错误
【Azure API 管理】在 Azure API 管理中使用 OAuth 2.0 授权和 Azure AD 保护 Web API 后端,在请求中携带Token访问后报401的错误
|
10月前
|
存储 网络协议 Linux
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
96 0

热门文章

最新文章