java – 如何在打包并部署为WAR的Springboot应用程序中启用异步支持
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 如何在打包并部署为WAR的Springboot应用程序中启用异步支持,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6372字,纯文字阅读大概需要10分钟。
内容图文
![java – 如何在打包并部署为WAR的Springboot应用程序中启用异步支持](/upload/InfoBanner/zyjiaocheng/810/343e9e9db0e9443a886848cd6157f8e7.jpg)
当我的SpringBoot应用程序从可执行JAR运行时,下面显示的以下REST端点按预期工作.也就是说,它将文本“我的测试响应”返回给客户端.但是,当我将相同的应用程序打包为WAR并部署到Tomcat(8.0.29)时,它会抛出以下异常:
There was an unexpected error (type=Internal Server Error, status=500).
Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding “true” to servlet and filter declarations in web.xml.
package my.rest.controllers;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
@RestController
@RequestMapping("/api/file")
public class FileContentRestController {
static final int BUFFER = 2048;
@RequestMapping(value = "/content", method = RequestMethod.GET)
@ResponseBody
public StreamingResponseBody getFileContent(HttpServletResponse response) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
final InputStream portalFileStream = new ByteArrayInputStream("My test response".getBytes());
return (OutputStream outputStream) -> {
int n;
byte[] buffer = new byte[1024];
while ((n = portalFileStream.read(buffer)) > -1) {
outputStream.write(buffer, 0, n);
}
portalFileStream.close();
};
}
}
我从here和其他地方的理解是,SpringBoot支持SpringBoot注册的所有过滤器和servlet的异步支持.当从具有嵌入式Tomcat容器的独立JAR运行时,情况肯定会出现这种情况.
如何在部署为WAR时确保启用异步支持?
我的SpringBoot应用程序配置如下:
package my;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class MyRestApp extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
public static void main(String[] args) throws JsonProcessingException {
configureApplication(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
return builder.sources(MyRestApp.class).bannerMode(Banner.Mode.OFF);
}
}
使用MVC配置:
package my;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@EnableAsync
public class MyMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(-1);
configurer.setTaskExecutor(asyncTaskExecutor());
}
@Bean
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("SpringAsyncThread-");
executor.initialize();
return executor;
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
最后,使用Maven使用以下POM构建和打包应用程序:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.acme</groupId>
<artifactId>my-rest-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>my-rest-app</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
<resource>
<directory>${project.build.directory}/generated-resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
解决方法:
那么你解析的异常就说明了一切:
There was an unexpected error (type=Internal Server Error, status=500). Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding “true” to servlet and filter declarations in web.xml.
因此,您需要在web.xml中启用它或(因为您使用的是spring-boot应用程序),您必须配置特定的bean.
也许这个AppConfig的代码片段会有所帮助
@Bean
public ServletRegistrationBean dispatcherServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new DispatcherServlet(), "/");
registration.setAsyncSupported(true);
return registration;
}
内容总结
以上是互联网集市为您收集整理的java – 如何在打包并部署为WAR的Springboot应用程序中启用异步支持全部内容,希望文章能够帮你解决java – 如何在打包并部署为WAR的Springboot应用程序中启用异步支持所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。