代码之家  ›  专栏  ›  技术社区  ›  Mohammed Fathi

@异步在spring中不工作

  •  1
  • Mohammed Fathi  · 技术社区  · 8 年前

    我有一个spring boot应用程序,想通过使用@async annotation运行一个简单的异步后台任务,但是,这似乎不起作用(没有创建新线程,我要等到每次调用函数后睡眠结束。 *****我的配置类:**

    @Configuration
    @EnableAsync
    public class AsyncConfig {
    
    }
    

    ****我的控制器:***

     @GetMapping(value = "/testAsync")
        @ResponseBody
        public String testAsync() {
    
            TestClass testClass = new TestClass();
            System.out.println("begin of test async dates is : " + new Date());
    
            for (int i = 0; i < 5; i++) {
    
                testClass.asyncMethod();
            }
            System.out.println("end of test async  dates is : " + new Date());
    
            return "end!";
        }
    

    *****我的testClass中的异步方法:**

    @Service
    public class TestClass {
    
        @Async
        public void asyncMethod() {
            System.out.println("Execute method asynchronously. in thread : "
                    + Thread.currentThread().getName());
    
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            System.out.println("after sleep : " + Thread.currentThread().getName());
        }
    }
    

    ****运行应用程序后输出:**

    begin of test async dates is : Sat Jul 14 19:35:43 EET 2018
    Execute method asynchronously. in thread : http-nio-8080-exec-1
    after sleep : http-nio-8080-exec-1
    Execute method asynchronously. in thread : http-nio-8080-exec-1
    after sleep : http-nio-8080-exec-1
    Execute method asynchronously. in thread : http-nio-8080-exec-1
    after sleep : http-nio-8080-exec-1
    Execute method asynchronously. in thread : http-nio-8080-exec-1
    2018-07-14 19:36:22.299  INFO 3120 --- [MessageBroker-1] o.s.w.s.c.WebSocketMessageBrokerStats    : WebSocketSession[0 current WS(0)-HttpStream(0)-HttpPoll(0), 0 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(0)-CONNECTED(0)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], outboundChannelpool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0], sockJsScheduler[pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
    after sleep : http-nio-8080-exec-1
    Execute method asynchronously. in thread : http-nio-8080-exec-1
    after sleep : http-nio-8080-exec-1
    end of test async  dates is : Sat Jul 14 19:36:33 EET 2018
    

    ****注:** -我试过用@component注释testclass,但它不起作用 -我尝试在应用程序级别和方法级别都添加一个执行器,但得到的结果相同。

    请帮帮我,我花了5个小时在这件事上,运气不好

    1 回复  |  直到 8 年前
        1
  •  2
  •   Nathan Hughes    8 年前

    将testClass自动连接到控制器中,使用testClass类型创建控制器的实例成员,并为其提供注释autowire。

    当您自己实例化它时,spring不知道异步注释,对它的调用将在调用线程中运行。