java - Spring Boot 使用 @EnableAsync 时不响应任何请求
问题描述
今天我用 Spring Boot 开始了一个新项目(一个简单的 MVC 项目)。从未将 Spring Boot 与 Thymeleaf 一起使用,但成功地用作带有注释的 REST 服务器(仅生成@Async
和使用@EnableAsync
JSON)。
一切正常(目前只有一个登录屏幕),但是当我放置@EnableAsync
注释时,“内部”服务器(Tomcat)不响应任何请求(连接被拒绝)。
如果我删除@EnableAsync
,一切都会再次完美运行。
下面是没有 @EnableAsync
的启动日志:
2018-05-02 16:29:43.370 INFO 17876 --- [ restartedMain] b.c.p.portal2j.Portal2jApplication : Starting Portal2jApplication on PROJETOS-20 with PID 17876 (D:\SIV2\Portal2j\target\classes started by correia in D:\SIV2\Portal2j)
2018-05-02 16:29:43.371 INFO 17876 --- [ restartedMain] b.c.p.portal2j.Portal2jApplication : No active profile set, falling back to default profiles: default
2018-05-02 16:29:43.564 INFO 17876 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@290dcac: startup date [Wed May 02 16:29:43 BRT 2018]; root of context hierarchy
2018-05-02 16:29:44.052 INFO 17876 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'templateEngine' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=portal2jApplication; factoryMethodName=templateEngine; initMethodName=null; destroyMethodName=(inferred); defined in br.com.projevias.portal2j.Portal2jApplication] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration; factoryMethodName=templateEngine; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.class]]
2018-05-02 16:29:44.483 INFO 17876 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 55425 (http)
2018-05-02 16:29:44.496 INFO 17876 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-02 16:29:44.496 INFO 17876 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-05-02 16:29:44.499 INFO 17876 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_152\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files (x86)\Microsoft Emulator Manager\1.0\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\nodejs\;C:\Windows\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\mvn\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files (x86)\Universal Extractor;C:\Program Files (x86)\Universal Extractor\bin;C:\ffmpeg\bin;C:\Users\correia\AppData\Local\Programs\Git\cmd;C:\Program Files (x86)\Yarn\bin\;C:\Users\correia\AppData\Local\Microsoft\WindowsApps;C:\Users\correia\AppData\Local\Programs\Git\cmd;C:\Users\correia\AppData\Roaming\npm;C:\Users\correia\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin;C:\mvn\bin;C:\Program Files\Heroku\bin;C:\Users\correia\AppData\Local\Yarn\bin;.]
2018-05-02 16:29:44.556 INFO 17876 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-02 16:29:44.556 INFO 17876 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 995 ms
2018-05-02 16:29:44.649 INFO 17876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-02 16:29:44.649 INFO 17876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-02 16:29:44.649 INFO 17876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-02 16:29:44.649 INFO 17876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-02 16:29:44.650 INFO 17876 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-05-02 16:29:44.650 INFO 17876 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-05-02 16:29:45.092 INFO 17876 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-02 16:29:45.123 INFO 17876 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:171}] to localhost:27017
2018-05-02 16:29:45.126 INFO 17876 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 1]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1626227}
2018-05-02 16:29:45.387 INFO 17876 --- [ restartedMain] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:172}] to localhost:27017
2018-05-02 16:29:45.646 INFO 17876 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-02 16:29:45.772 INFO 17876 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@290dcac: startup date [Wed May 02 16:29:43 BRT 2018]; root of context hierarchy
2018-05-02 16:29:45.823 INFO 17876 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/registro],methods=[GET]}" onto public java.util.concurrent.CompletableFuture<org.springframework.web.servlet.ModelAndView> br.com.projevias.portal2j.module.authentication.controllers.AuthController.registrarForm()
2018-05-02 16:29:45.825 INFO 17876 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto public java.lang.String br.com.projevias.portal2j.module.authentication.controllers.AuthController.efetuarLogin(br.com.projevias.portal2j.module.authentication.domain.dto.LoginDto,org.springframework.validation.BindingResult)
2018-05-02 16:29:45.825 INFO 17876 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String br.com.projevias.portal2j.module.authentication.controllers.AuthController.loginForm(org.springframework.ui.Model)
2018-05-02 16:29:45.827 INFO 17876 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-02 16:29:45.828 INFO 17876 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-02 16:29:45.843 INFO 17876 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-02 16:29:45.843 INFO 17876 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-02 16:29:46.071 INFO 17876 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@266e2b27, org.springframework.security.web.context.SecurityContextPersistenceFilter@10e7e39f, org.springframework.security.web.header.HeaderWriterFilter@6f4918a6, org.springframework.security.web.csrf.CsrfFilter@7b401338, org.springframework.security.web.authentication.logout.LogoutFilter@abda55, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3c2d4397, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@3d7bac59, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@ce25252, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@39a50991, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@77c658a5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5fc9fa07, org.springframework.security.web.session.SessionManagementFilter@1d496ecd, org.springframework.security.web.access.ExceptionTranslationFilter@11aa5c85, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@f283182]
2018-05-02 16:29:46.122 INFO 17876 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-05-02 16:29:46.144 INFO 17876 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-05-02 16:29:46.170 INFO 17876 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 55425 (http) with context path ''
2018-05-02 16:29:46.172 INFO 17876 --- [ restartedMain] b.c.p.portal2j.Portal2jApplication : Started Portal2jApplication in 3.031 seconds (JVM running for 3.662)
这里是我使用时的开始日志@EnableAsync
:
2018-05-02 16:58:42.682 INFO 8248 --- [ restartedMain] b.c.p.portal2j.Portal2jApplication : Starting Portal2jApplication on PROJETOS-20 with PID 8248 (D:\SIV2\Portal2j\target\classes started by correia in D:\SIV2\Portal2j)
2018-05-02 16:58:42.683 INFO 8248 --- [ restartedMain] b.c.p.portal2j.Portal2jApplication : No active profile set, falling back to default profiles: default
2018-05-02 16:58:42.898 INFO 8248 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6ed7bc81: startup date [Wed May 02 16:58:42 BRT 2018]; root of context hierarchy
2018-05-02 16:58:43.447 INFO 8248 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'templateEngine' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=portal2jApplication; factoryMethodName=templateEngine; initMethodName=null; destroyMethodName=(inferred); defined in br.com.projevias.portal2j.Portal2jApplication] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration; factoryMethodName=templateEngine; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.class]]
2018-05-02 16:58:43.622 INFO 8248 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'myConfig' of type [br.com.projevias.portal2j.module.core.config.MyConfig$$EnhancerBySpringCGLIB$$c88dda26] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-05-02 16:58:43.896 INFO 8248 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 55425 (http)
2018-05-02 16:58:43.910 INFO 8248 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-05-02 16:58:43.910 INFO 8248 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-05-02 16:58:43.912 INFO 8248 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_152\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files (x86)\Microsoft Emulator Manager\1.0\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\nodejs\;C:\Windows\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\mvn\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files (x86)\Universal Extractor;C:\Program Files (x86)\Universal Extractor\bin;C:\ffmpeg\bin;C:\Users\correia\AppData\Local\Programs\Git\cmd;C:\Program Files (x86)\Yarn\bin\;C:\Users\correia\AppData\Local\Microsoft\WindowsApps;C:\Users\correia\AppData\Local\Programs\Git\cmd;C:\Users\correia\AppData\Roaming\npm;C:\Users\correia\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin;C:\mvn\bin;C:\Program Files\Heroku\bin;C:\Users\correia\AppData\Local\Yarn\bin;.]
2018-05-02 16:58:43.967 INFO 8248 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-05-02 16:58:43.967 INFO 8248 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1072 ms
2018-05-02 16:58:44.049 INFO 8248 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-02 16:58:44.049 INFO 8248 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-05-02 16:58:44.049 INFO 8248 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-05-02 16:58:44.503 INFO 8248 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-02 16:58:44.537 INFO 8248 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:193}] to localhost:27017
2018-05-02 16:58:44.540 INFO 8248 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 1]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1757374}
2018-05-02 16:58:44.809 INFO 8248 --- [ restartedMain] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:194}] to localhost:27017
2018-05-02 16:58:44.833 INFO 8248 --- [ restartedMain] .s.a.AnnotationAsyncExecutionInterceptor : No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
查看启用异步的日志,我没有看到任何SimpleUrlHandlerMapping
和RequestMappingHandlerAdapter
. 最后一行引起了我的注意No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
,因此,我使用了以下代码:
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("p2j");
executor.initialize();
return executor;
}
现在,关于“no bean of type TaskExecutor”的行没有出现,并且有两个新的日志条目:
2018-05-02 17:01:25.521 INFO 14084 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService
2018-05-02 17:01:25.525 INFO 14084 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'threadPoolTaskExecutor'
但是,服务器仍然没有响应任何请求。
PS:这是主要课程:
@SpringBootApplication
@EnableAutoConfiguration
@EnableWebMvc
public class Portal2jApplication {
public static void main(String[] args) {
SpringApplication.run(Portal2jApplication.class, args);
}
}
更新: 这是我的存储库界面:
@Repository
public interface UsuarioRepo extends MongoRepository<Usuario, String> {
@Async
CompletableFuture<Usuario> findByEmail(String email);
}
由于某种原因我不记得了:P,我@Async
在接口上使用了注释,并且根据此页面:http ://www.baeldung.com/spring-async ,@Async
必须仅应用于公共方法。
从存储库中删除@Async
,并在正确的位置(在 a 中Service
)使用,一切都再次完美运行。真的不知道这是否是“错误”!
解决方案
我不知道@Aysnc
您的存储库支持这一点,而且我认为您通常并不真正想要它,因为它会强制对您的存储库的每次调用都包含在 Future 中。这会造成开销分配,因为这是使用线程的低效方式。
您可以将存储库包装在具有这些注释的组件中,这对于需要很长时间的存储库方法是有意义的。但是,除非有充分的理由,否则我会将需要很长时间才能执行的 repo 方法视为代码异味。
推荐阅读
- go - Keep-alive:死节点检测
- arrays - 如何遍历具有不同类型的类数组并快速打印它们的属性?
- mongodb - 在 Julia 中使用 SSL 证书连接到 Mongodb
- python - 通过字符串调用函数
- jquery - 加载页面时如何加载模式
- c# - System.InvalidOperationException:没有进程与此对象关联
- python - Python在父初始化中创建子对象并访问父属性
- azure-devops - 在 Azure DevOps 中设置权限
- html - 将复选框与标签对齐并为选中的复选框添加背景颜色
- android - Admob 广告未显示在我的 Android 应用中