Spring系列第37篇:@EnableAsync &

这篇博客介绍了Spring中@EnableAsync的使用,包括无返回值和有返回值的异步方法,以及如何自定义线程池和处理异常。通过案例展示了如何实现异步日志记录和商品信息获取,讨论了异步执行的性能提升。此外,还详细说明了自定义异常处理的两种情况,分别是返回Future时的异常捕获和无返回值时的异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. @EnableAsync添加在spring配置类上,此时@Async注解才会起效。

常见2种用法

  1. 无返回值的

  2. 可以获取返回值的

4、无返回值的


用法

方法返回值不是Future类型的,被执行时,会立即返回,并且无法获取方法返回值,如:

@Async

public void log(String msg) throws InterruptedException {

System.out.println(“开始记录日志,” + System.currentTimeMillis());

//模拟耗时2秒

TimeUnit.SECONDS.sleep(2);

System.out.println(“日志记录完毕,” + System.currentTimeMillis());

}

案例

实现日志异步记录的功能。

LogService.log方法用来异步记录日志,需要使用@Async标注

package com.javacode2018.async.demo1;

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component

public class LogService {

@Async

public void log(String msg) throws InterruptedException {

System.out.println(Thread.currentThread() + “开始记录日志,” + System.currentTimeMillis());

//模拟耗时2秒

TimeUnit.SECONDS.sleep(2);

System.out.println(Thread.currentThread() + “日志记录完毕,” + System.currentTimeMillis());

}

}

来个spring配置类,需要加上@EnableAsync开启bean方法的异步调用.

package com.javacode2018.async.demo1;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.EnableAspectJAutoProxy;

import org.springframework.scheduling.annotation.EnableAsync;

@ComponentScan

@EnableAsync

public class MainConfig1 {

}

测试代码

package com.javacode2018.async;

import com.javacode2018.async.demo1.LogService;

import com.javacode2018.async.demo1.MainConfig1;

import org.junit.Test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.concurrent.TimeUnit;

public class AsyncTest {

@Test

public void test1() throws InterruptedException {

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

context.register(MainConfig1.class);

context.refresh();

LogService logService = context.getBean(LogService.class);

System.out.println(Thread.currentThread() + " logService.log start," + System.currentTimeMillis());

logService.log(“异步执行方法!”);

System.out.println(Thread.currentThread() + " logService.log end," + System.currentTimeMillis());

//休眠一下,防止@Test退出

TimeUnit.SECONDS.sleep(3);

}

}

运行输出

Thread[main,5,main] logService.log start,1595223990417

Thread[main,5,main] logService.log end,1595223990432

Thread[SimpleAsyncTaskExecutor-1,5,main]开始记录日志,1595223990443

Thread[SimpleAsyncTaskExecutor-1,5,main]日志记录完毕,1595223992443

前2行输出,可以看出logService.log立即就返回了,后面2行来自于log方法,相差2秒左右。

前面2行在主线程中执行,后面2行在异步线程中执行。

5、获取异步返回值


用法

若需取异步执行结果,方法返回值必须为Future

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值