spring boot實現異步調用


今天在這里學習下使用springboot的異步調用async

首先使用@EnableAsync開啟異步功能

/**
* @author fengzp
 * @date 17/5/8
 * @email fengzp@gzyitop.com
 * @company 廣州易站通計算機科技有限公司
 */
@SpringBootApplication
@EnableAsync
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

測試類

    /**
 * @author fengzp
 * @date 17/5/8
 * @email fengzp@gzyitop.com
 * @company 廣州易站通計算機科技有限公司
 */
@Component
public class AsyncTest {

    public static Random random =new Random();

    /**
	 * @Async所修飾的函數不要定義為static類型,否則異步調用不會生效
	 *
	 * 這里通過返回Future<T>來返回異步調用的結果,實現異步回調
	 */
	@Async
	public Future<String> test1() throws InterruptedException {
	    System.out.println("test1 begin");
	    long begin = System.currentTimeMillis();
	    Thread.sleep(random.nextInt(10000));
	    System.out.println("test1 end " + (System.currentTimeMillis() - begin));
	    return new AsyncResult<String>("test1 is done!");
	}

    @Async
    public Future<String> test2() throws InterruptedException {
        System.out.println("test2 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("test2 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("test2 is done!");
    }

    @Async
    public Future<String> test3() throws InterruptedException {
        System.out.println("test3 begin");
        long begin = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        System.out.println("test3 end " + (System.currentTimeMillis() - begin));
        return new AsyncResult<String>("test3 is done!");
    }
}

測試

/**
 * @author fengzp
 * @date 17/5/8
 * @email fengzp@gzyitop.com
 * @company 廣州易站通計算機科技有限公司
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class Test {

    @Autowired
    AsyncTest asyncTest;

    @org.junit.Test
    public void test() throws InterruptedException {
        System.out.println("begin");
        long begin = System.currentTimeMillis();
        Future<String> test1 = asyncTest.test1();
        Future<String> test2 = asyncTest.test2();
        Future<String> test3 = asyncTest.test3();

        while(true) {
            if(test1.isDone() && test2.isDone() && test3.isDone())
                break;

            Thread.sleep(500);
        }

        System.out.println("end 耗時: " + (System.currentTimeMillis() - begin));
    }
}

運行結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM