简介

异步调用针对的是同步调用,一般在代码中我们使用同步调用相对较多,即请求代码立即返回结果或者说执行代码,异步调用则是指请求之后不会里面返回结果或者是调用代码 注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

看完本章你将会知道

如何构建一个异步程序,区分出同步和异步之间的区别

配置文件

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.boot</groupId>
    <artifactId>demo-async</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo-async</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

HelloAsync

项目结构图

image.png

ReturnAsyncTask

package com.boot.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

@Slf4j
@Component
public class ReturnAsyncTask {
    public static final Random random = new Random();


    /**
     * @return 执行该程序所需时间
     * @throws Exception
     */
    @Async
    public Future<Long> first() throws Exception {
        log.info("first start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("firse end,date:{}", (end - start));
        return new AsyncResult<>(end - start);
    }

    @Async
    public Future<Long> second() throws Exception {
        log.info("second start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("second end,date:{}", (end - start));
        return new AsyncResult<>(end - start);
    }

    @Async
    public Future<Long> thirdly() throws Exception {
        log.info("thirdly start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("thirdly end,date:{}", (end - start));
        return new AsyncResult<>(end - start);
    }
}

SynchronizationTask

package com.boot.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Random;

@Slf4j
@Component
public class SynchronizationTask {
    public static final Random random = new Random();

    public void first() throws Exception {
        log.info("first start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("firse end,date:{}", (end - start));
    }

    public void second() throws Exception {
        log.info("second start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("second end,date:{}", (end - start));
    }

    public void thirdly() throws Exception {
        log.info("thirdly start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("thirdly end,date:{}", (end - start));
    }
}

VoidAsyncTask

package com.boot.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Random;

@Slf4j
@Component
public class VoidAsyncTask {
    public static final Random random = new Random();

    @Async
    public void first() throws Exception {
        log.info("first start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("firse end,date:{}", (end - start));
    }

    @Async
    public void second() throws Exception {
        log.info("second start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("second end,date:{}", (end - start));
    }

    @Async
    public void thirdly() throws Exception {
        log.info("thirdly start");
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(5000));
        long end = System.currentTimeMillis();
        log.info("thirdly end,date:{}", (end - start));
    }
}

DemoAsyncApplicationTests

package com.boot;

import com.boot.task.ReturnAsyncTask;
import com.boot.task.VoidAsyncTask;
import com.boot.task.SynchronizationTask;
import lombok.extern.slf4j.Slf4j;
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.EnableAsync;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.Future;

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAsync //异步需要在启动类上面加上此注解
public class DemoAsyncApplicationTests {
    @Autowired
    private SynchronizationTask synchronizationTask;
    @Autowired
    private VoidAsyncTask voidAsyncTask;
    @Autowired
    private ReturnAsyncTask returnAsyncTask;

    /**
     * @throws Exception
     * 同步调用
     */
    @Test
    public void synchronizationTask() throws Exception {
        long start = System.currentTimeMillis();
        synchronizationTask.first();
        synchronizationTask.second();
        synchronizationTask.thirdly();
        long end = System.currentTimeMillis();
        log.info("同步总时间:{}", (end - start));
    }
    /**
     * @throws Exception
     * 异步调用
     * 主程序在启用之后是没有管理方法是否已经执行完毕,所以异步是没有返回值的,log也就不会被打印出来
     */
    @Test
    public void asyncTask() throws Exception {
        long start = System.currentTimeMillis();
        voidAsyncTask.first();
        voidAsyncTask.second();
        voidAsyncTask.thirdly();
        long end = System.currentTimeMillis();
        log.info("异步总时间:{}", (end - start));
    }

    /**
     * 有返回值的异步调用
     * @throws Exception
     */
    @Test
    public void returnAsyncTask() throws Exception {
        long start = System.currentTimeMillis();
        Future<Long> first = returnAsyncTask.first();
        Future<Long> second = returnAsyncTask.second();
        Future<Long> thirdly = returnAsyncTask.thirdly();

        while(true) {
            if(first.isDone() && second.isDone() && thirdly.isDone()) {
                // 三个任务都调用完成,退出循环等待
                break;
            }
            Thread.sleep(1000);
        }


        long end = System.currentTimeMillis();
        log.info("异步总时间:{}", (first.get()+second.get()+thirdly.get()));
        log.info("returnAsyncTask 耗时:{}", (end - start));
    }

}

run(returnAsyncTask)

image.png

git地址

gitee

Last Updated: 6/13/2019, 7:10:41 PM