SpringBoot系列之异步任务@Async使用教程

SpringBoot系列之异步任务@Async使用教程

      • 实验环境准备
      • github用户信息类
      • 异步任务配置类
      • 查询github用户信息业务类
      • 启动测试类实现
      • 自定义异步任务异常

例子来自国外的两篇博客:

  • https://www.baeldung.com/spring-async
  • https://spring.io/guides/gs/async-method/

ps:不按照原文进行翻译,根据自己的实践,整合两篇博客,进行说明Springboot异步任务的使用,本博客可以作为异步任务的学习参考

实验环境准备

  • JDK 1.8
  • SpringBoot2.2.1
  • Maven 3.2+
  • 开发工具
    • IntelliJ IDEA
    • smartGit

创建一个SpringBoot Initialize项目,详情可以参考我之前博客:SpringBoot系列之快速创建项目教程

pom.xml:


<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.1.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.example.springbootgroupId>
    <artifactId>springboot-asyncartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>springboot-asyncname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

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

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

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

project>

github用户信息类

@JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段,可以满足当前的需要。

package com.example.springboot.async.bean;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;

import java.io.Serializable;

/**
 * 
 *  用户信息实体类
 *  Copy @ https://spring.io/guides/gs/async-method/
 * 
* *
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/07/20 10:14  修改内容:
 * 
*/
@JsonIgnoreProperties(ignoreUnknown = true) @Data public class User implements Serializable { private String name; private String blog; @Override public String toString() { return "User{" + "name='" + name + '\'' + ", blog='" + blog + '\'' + '}'; } }

异步任务配置类

可以实现AsyncConfigurerSupport 类,也可以使用@Bean(name = "threadPoolTaskExecutor")的方法,这里定义了线程池的配置

package com.example.springboot.async.config;

import com.example.springboot.async.exception.CustomAsyncExceptionHandler;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 
 *  AsyncConfiguration
 *  Copy @https://spring.io/guides/gs/async-method/
 * 
* *
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/07/20 10:12  修改内容:
 * 
*/
@Configuration @EnableAsync public class AsyncConfiguration extends AsyncConfigurerSupport { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(2); executor.setQueueCapacity(500); executor.setThreadNamePrefix("GithubLookup-"); executor.initialize(); return executor; } /*@Bean(name = "threadPoolTaskExecutor") public Executor threadPoolTaskExecutor() { return new ThreadPoolTaskExecutor(); }*/ }

查询github用户信息业务类

使用Future获得异步执行结果时,要么调用阻塞方法get(),要么轮询看isDone()是否为true,这两种方法都不是很好,因为主线程也会被迫等待。

在Java8中,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,并且提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合 CompletableFuture 的方法。

package com.example.springboot.async.service;

import com.example.springboot.async.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * 
 *  GitHubLookupService
 * copy @https://spring.io/guides/gs/async-method/
 * 
* *
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/07/20 10:18  修改内容:
 * 
*/
@Service public class GitHubLookupService { private static final Logger LOG = LoggerFactory.getLogger(GitHubLookupService.class); private final RestTemplate restTemplate; public GitHubLookupService(RestTemplateBuilder restTemplateBuilder) { this.restTemplate = restTemplateBuilder.build(); } @Async //@Async("threadPoolTaskExecutor") public Future<User> findUser(String user) throws InterruptedException { LOG.info("Looking up " + user); String url = String.format("https://api.github.com/users/%s", user); User results = restTemplate.getForObject(url, User.class); // Artificial delay of 1s for demonstration purposes Thread.sleep(1000L); return CompletableFuture.completedFuture(results); } }

启动测试类实现

实现CommandLineRunner 接口,SpringBoot启动时候,会自动调用,也可以用@Order指定执行顺序

package com.example.springboot.async.service;

import com.example.springboot.async.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

/**
 * 
 *  CommandLineRunner
 *  Copy @https://spring.io/guides/gs/async-method/
 * 
* *
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/07/20 10:25  修改内容:
 * 
*/
@Component public class AppRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(AppRunner.class); @Autowired GitHubLookupService gitHubLookupService; @Override public void run(String... args) throws Exception { // Start the clock long start = System.currentTimeMillis(); // Kick of multiple, asynchronous lookups Future<User> page1 = gitHubLookupService.findUser("PivotalSoftware"); Future<User> page2 = gitHubLookupService.findUser("CloudFoundry"); Future<User> page3 = gitHubLookupService.findUser("Spring-Projects"); // Wait until they are all done while (!(page1.isDone() && page2.isDone() && page3.isDone())) { Thread.sleep(10); //10-millisecond pause between each check } // Print results, including elapsed time logger.info("Elapsed time: " + (System.currentTimeMillis() - start)); logger.info("--> " + page1.get()); logger.info("--> " + page2.get()); logger.info("--> " + page3.get()); } }

自定义异步任务异常

当方法返回类型为Future时,异常处理很容易– Future.get()方法将引发异常。但是,如果返回类型为void,则异常不会传播到调用线程。因此,我们需要添加额外的配置来处理异常。我们将通过实现AsyncUncaughtExceptionHandler接口来创建自定义异步异常处理程序。

package com.example.springboot.async.exception;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import java.lang.reflect.Method;

/**
 * 
 *  Copy @ https://www.baeldung.com/spring-async
 * 
* *
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2020/07/20 11:08  修改内容:
 * 
*/
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler { @Override public void handleUncaughtException( Throwable throwable, Method method, Object... obj) { System.out.println("Exception message - " + throwable.getMessage()); System.out.println("Method name - " + method.getName()); for (Object param : obj) { System.out.println("Parameter value - " + param); } } }

需要重写getAsyncUncaughtExceptionHandler()方法以返回我们的自定义异步异常处理程序

@Configuration
@EnableAsync
public class AsyncConfiguration extends AsyncConfigurerSupport  {

 	// ...

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }
}

启动之后,可以看到如下信息,因为是多线程方式,所以都不是在main线程里的,异步执行的
SpringBoot系列之异步任务@Async使用教程_第1张图片
如果注释@Async注解,再次启动,会发现都在main主线程里执行程序
SpringBoot系列之异步任务@Async使用教程_第2张图片

代码例子下载:code download

你可能感兴趣的:(SpringBoot,spring,spring,boot,多线程,异步,Async)