新聞中心
這篇文章給大家介紹異步請求如何利用Spring Boot來實現(xiàn),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
成都創(chuàng)新互聯(lián)主要從事網(wǎng)站設(shè)計、成都做網(wǎng)站、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)邱縣,10余年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108
首先說一下幾個要點:
1、@WebFilter 和 @WebServlet 注解中的 asyncSupported = true 屬性
異步處理的servlet若存在過濾器,則過濾器的注解@WebFilter應(yīng)設(shè)置asyncSupported=true,
否則會報錯 A filter or servlet of the current chain does not support asynchronous operations.
2、@EnableAsync 注解
Spring Boot 默認(rèn)添加了一些攔截 /* 的過濾器,因為 /* 會攔截所有請求,按理說我們也要設(shè)置 asyncSupported=true 屬性。因為這些過濾器都是 Spring Boot 初始化的,所以它提供了 @EnableAsync 注解來統(tǒng)一配置,該注解只針對 “非 @WebFilter 和 @WebServlet 注解的有效”,所以我們自己定義的 Filter 還是需要自己配置 asyncSupported=true 的。
3、AsyncContext 對象
獲取一個異步請求的上下文對象。
4、asyncContext.setTimeout(20 * 1000L);
我們不能讓異步請求無限的等待下去,通過 setTimeout 來設(shè)定最大超時時間。
下面通過兩種方式來測試異步任務(wù):
先在 SpringBootSampleApplication 上添加 @EnableAsync 注解。
再檢查所有自定義的Filter,如存在如下兩種情況需要配置 asyncSupported=true
1) 自定義Filter 攔截了 /*
2) 某Filter 攔截了 /shanhy/* ,我們需要執(zhí)行的異步請求的 Servlet 為 /shanhy/testcomet
方法一:原生Servlet方式
package org.springboot.sample.servlet; import java.io.IOException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * HTTP長連接實現(xiàn) * * @author 單紅宇(365384722) * @myblog http://blog.csdn.net/catoop/ * @create 2016年3月29日 */ @WebServlet(urlPatterns = "/xs/cometservlet", asyncSupported = true) //異步處理的servlet若存在過濾器,則過濾器的注解@WebFilter應(yīng)設(shè)置asyncSupported=true, //否則會報錯A filter or servlet of the current chain does not support asynchronous operations. public class CometServlet extends HttpServlet { private static final long serialVersionUID = -8685285401859800066L; private final QueueasyncContexts = new LinkedBlockingQueue<>(); private final Thread generator = new Thread("Async Event generator") { @Override public void run() { while (!generator.isInterrupted()) {// 線程有效 try { while (!asyncContexts.isEmpty()) {// 不為空 TimeUnit.SECONDS.sleep(10);// 秒,模擬耗時操作 AsyncContext asyncContext = asyncContexts.poll(); HttpServletResponse res = (HttpServletResponse) asyncContext.getResponse(); res.getWriter().write("{\"result\":\"OK - "+System.currentTimeMillis()+"\"}"); res.setStatus(HttpServletResponse.SC_OK); res.setContentType("application/json"); asyncContext.complete();// 完成 } } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }; @Override public void init() throws ServletException { super.init(); generator.start(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(">>>>>>>>>>CometServlet Request<<<<<<<<<<<"); doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext asyncContext = req.startAsync(); asyncContext.setTimeout(20 * 1000L); asyncContexts.offer(asyncContext); } @Override public void destroy() { super.destroy(); generator.interrupt(); } }
方法二:Controller 方式
@Controller public class PageController { @RequestMapping("/async/test") @ResponseBody public Callablecallable() { // 這么做的好處避免web server的連接池被長期占用而引起性能問題, // 調(diào)用后生成一個非web的服務(wù)線程來處理,增加web服務(wù)器的吞吐量。 return new Callable () { @Override public String call() throws Exception { Thread.sleep(3 * 1000L); return "小單 - " + System.currentTimeMillis(); } }; } }
最后寫一個comet.jsp頁面測試:
<%@ page pageEncoding="UTF-8"%>長連接測試 長連接測試
關(guān)于異步請求如何利用Spring Boot來實現(xiàn)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網(wǎng)站名稱:異步請求如何利用SpringBoot來實現(xiàn)
文章路徑:http://www.dlmjj.cn/article/isjodh.html