SpringBoot异步调用(Async Call)

2018-06-21

异步调用在开发中经常使用,本文通过一个简单的例子快速了解异步调用在SpringBoot中是如何使用的。

编码实现

Create Project

<?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.wuwenze</groupId>
    <artifactId>springboot-async-examples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </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>

TaskExecutor Bean

package com.wuwenze.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author wwz
 * @version 1 (2018/6/21)
 * @since Java7
 */
@Configuration
public class AsyncTaskConfig {

    @Bean
    public AsyncTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("Async-Executor-Example");
        executor.setMaxPoolSize(10);
        executor.setCorePoolSize(3);
        // 使用预定义的异常处理类
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //...
        return executor;
    }
}

AsyncTask Examples

package com.wuwenze.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.concurrent.Future;

/**
 * @author wwz
 * @version 1 (2018/6/21)
 * @since Java7
 */
@Slf4j
@Component
public class AsyncTaskDemo {

    @Async
    public void test1() {
        log.debug("com.wuwenze.task.AsyncTaskDemo#test1(): 常规异步调用,不含参数和返回值");
    }

    @Async
    public void test2(String name) {
        log.debug("com.wuwenze.task.AsyncTaskDemo#test2(): 常规异步调用,可接收参数:name = {}", name);
    }

    @Async
    public Future<String> test3(String name) {
        log.debug("com.wuwenze.task.AsyncTaskDemo#test3(): 可接收参数以及返回值:name = {}", name);

        return new AsyncResult<>(String.format("hello, %s", name));
    }
}

单元测试

package com.wuwenze.task;

import com.wuwenze.SpringbootAsyncExamplesApplication;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author wwz
 * @version 1 (2018/6/21)
 * @since Java7
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootAsyncExamplesApplication.class)
public class AsyncTaskDemoTest {

    @Resource
    AsyncTaskDemo asyncTaskDemo;

    @Test
    public void testAsyncMethods() throws ExecutionException, InterruptedException {
        asyncTaskDemo.test1();
        asyncTaskDemo.test2("china");

        Future<String> future = asyncTaskDemo.test3("wuwenze");
        log.debug("test3() 接收返回值:future: {}", future.get());
    }
}

最终结果打印

2018-06-21 22:16:32.324 DEBUG 5388 --- [ecutor-Example1] com.wuwenze.task.AsyncTaskDemo           : com.wuwenze.task.AsyncTaskDemo#test1(): 常规异步调用,不含参数和返回值
2018-06-21 22:16:32.324 DEBUG 5388 --- [ecutor-Example2] com.wuwenze.task.AsyncTaskDemo           : com.wuwenze.task.AsyncTaskDemo#test2(): 常规异步调用,可接收参数:name = china
2018-06-21 22:16:32.324 DEBUG 5388 --- [ecutor-Example3] com.wuwenze.task.AsyncTaskDemo           : com.wuwenze.task.AsyncTaskDemo#test3(): 可接收参数以及返回值:name = wuwenze
2018-06-21 22:16:32.325 DEBUG 5388 --- [           main] com.wuwenze.task.AsyncTaskDemoTest       : test3() 接收返回值:future: hello, wuwenze