1. 程式人生 > >spring boot非同步執行@Async

spring boot非同步執行@Async

1.一般非同步執行,使用多執行緒,或者訊息中介軟體完成

2.spring [email protected]可以讓方法非同步執行

package com.example.demo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class A {
    @Async
    public void contextLoads() {

        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        System.out.println("begin:"+format.format(new Date()));
        try {
            Thread.sleep(5*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end:"+format.format(new Date()));
    }
}
package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

@Autowired
A a;

	@Test
	public void a() throws InterruptedException {
		SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
		System.out.println("開始:"+format.format(new Date()));
		a.contextLoads();
		System.out.println("結束:"+format.format(new Date()));
		Thread.sleep(10 * 1000);
	}

}

再啟動類加上

@EnableAsync
public class DemoApplication  {

執行效果:

開始:22:38:45
2018-09-17 22:38:45.430  INFO 7816 --- [           main] .s.a.AnnotationAsyncExecutionInterceptor : No TaskExecutor bean found for async processing
結束:22:38:45
begin:22:38:45
end:22:38:50

可以看出它是不等函式執行完畢就進行下一步的

看下同步情況下,也就是去掉@Async

執行效果:

開始:22:58:39
begin:22:58:39
end:22:58:44
結束:22:58:44

注意點:

@Async必須放在2個不同類中

啟動類要加上@EnableAsync