使用@EnableAsync时,Spring Boot不响应任何请求

时间:2018-05-02 20:07:11

标签: java spring spring-boot asynchronous

今天我用Spring Boot(一个简单的MVC项目)开始了一个新项目。 从未在Thymeleaf中使用Spring Boot,但成功用作具有@Async@EnableAsync注释的REST服务器(仅生成并使用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

查看启用了异步的日志,我看不到任何SimpleUrlHandlerMappingRequestMappingHandlerAdapter。 最后一行引起了我的注意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;
}

现在,关于&#34;没有类型的TaskExecutor&#34;不会出现,并有两个新的日志条目:

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,并在正确的位置使用(在Service中),每个方法都可以完美地运行。不要真的知道这是&#34;错误&#34;!

1 个答案:

答案 0 :(得分:0)

我不知道您的存储库支持@Aysnc,而且我不认为您一般都想要这样做,因为它会强制执行每次调用您的存储库的操作在未来。这会产生大量的开销,因为它是一种使用线程的低效方式。

您可以将您的存储库包装在具有这些注释的组件中,这对于需要很长时间的repo方法是有意义的。然而,我会认为一个repo方法需要花费很长时间才能作为代码气味执行,除非有很好的理由。