当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot 中如何支持异步方法

Spring Boot 中如何支持异步方法

2019年10月12日  | 移动技术网IT编程  | 我要评论

本人免费整理了java高级资料,涵盖了java、redis、mongodb、mysql、zookeeper、spring cloud、dubbo高并发分布式等教程,一共30g,需要自己领取。
传送门:https://mp.weixin.qq.com/s/jzddfh-7ynudmkjt0irl8q

  • 异步用法
  • @enableasync 注解
  • @async 注解
  • 明确指定执行器
  • 管理 @async 的异常

异步用法

@enableasync 注解

要使用 @async,首先需要使用 @enableasync 注解开启 spring boot 中的异步特性。

@configuration
@enableasync
public class appconfig {
}

 

更详细的配置说明,可以参考:asyncconfigurer

@async 注解

支持的用法

(1)无入参无返回值方法

您可以用 @async 注解修饰方法,这表明这个方法是异步方式调用。换句话说,程序在调用此方法时会立即返回,而方法的实际执行发生在已提交给 spring taskexecutor 的任务中。在最简单的情况下,您可以将注解应用于返回 void 的方法,如以下示例所示:

@async
void dosomething() {
    // this will be executed asynchronously
}

 

(2)有入参无返回值方法

与使用 @scheduled 注释注释的方法不同,这些方法可以指定参数,因为它们在运行时由调用者以“正常”方式调用,而不是由容器管理的调度任务调用。例如,以下代码是 @async 注解的合法应用:

@async
void dosomething(string s) {
    // this will be executed asynchronously
}

 

(3)有入参有返回值方法

甚至可以异步调用返回值的方法。但是,这些方法需要具有 future 类型的返回值。这仍然提供了异步执行的好处,以便调用者可以在调用 future 上的 get() 之前执行其他任务。以下示例显示如何在返回值的方法上使用@async

@async
future<string> returnsomething(int i) {
    // this will be executed asynchronously
}

 

不支持的用法

@async 不能与生命周期回调一起使用,例如 @postconstruct

要异步初始化 spring bean,必须使用单独的初始化 spring bean,然后在目标上调用 @async带注释的方法,如以下示例所示:

public class samplebeanimpl implements samplebean {

    @async
    void dosomething() {
        // ...
    }

}

public class samplebeaninitializer {

    private final samplebean bean;

    public samplebeaninitializer(samplebean bean) {
        this.bean = bean;
    }

    @postconstruct
    public void initialize() {
        bean.dosomething();
    }

}

 

明确指定执行器

默认情况下,在方法上指定 @async 时,使用的执行器是在启用异步支持时配置的执行器,即如果使用 xml 或 asyncconfigurer 实现(如果有),则为“annotation-driven”元素。但是,如果需要指示在执行给定方法时应使用默认值以外的执行器,则可以使用 @async 注解的 value 属性。以下示例显示了如何执行此操作:

@async("otherexecutor")
void dosomething(string s) {
    // this will be executed asynchronously by "otherexecutor"
}

 

在这种情况下,“otherexecutor”可以是 spring 容器中任何 executor bean 的名称,也可以是与任何 executor 关联的限定符的名称(例如,使用 <qualifier> 元素或 spring 的 @qualifier 注释指定) )。

管理 @async 的异常

当 @async 方法的返回值类型为 future 型时,很容易管理在方法执行期间抛出的异常,因为在调用 get 结果时会抛出此异常。但是,对于返回值类型为 void 型的方法,异常不会被捕获且无法传输。您可以提供 asyncuncaughtexceptionhandler来处理此类异常。以下示例显示了如何执行此操作:

public class myasyncuncaughtexceptionhandler implements asyncuncaughtexceptionhandler {

    @override
    public void handleuncaughtexception(throwable ex, method method, object... params) {
        // handle exception
    }
}

 

默认情况下,仅记录异常。您可以使用 asyncconfigurer 或 <task:annotation-driven />xml元素定义自定义 asyncuncaughtexceptionhandler

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网