SpringBoot之@Async,异步任务

SpringBoot之@Async异步任务

SpringBoot实现异步任务首先要开启异步

@EnableAsync
@SpringBootApplication
public class AsyncdemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(AsyncdemoApplication.class, args);
	}
}

异步任务没有返回值时:

controller代码:

@Controller
public class TestOneController {
	@Autowired
	private TestOneService testOneService;

	@RequestMapping("/hello")
	public String getString()  {
		try {
			testOneService.hi();
			System.out.println("--------");
			System.out.println(Thread.currentThread().getName()+"2");
		}
		catch (Exception e){
			e.printStackTrace();
		}
		return "error";
	}
}

service代码:

@Service
public class TestOneService {
	@Async
	public  void  hi() throws InterruptedException {
		Thread.sleep(10000);
		System.out.println(Thread.currentThread().getName()+"1");
	}
}

运行结果:

--------
http-nio-8081-exec-52
task-91

注意,亲测异步任务不能写在controller里面

异步任务有返回值时:

controller代码:

@Controller
public class TestTwoController {
	@Autowired
	private TestTwoService testTwoService;

	@GetMapping("/hello1")
	public  Map<String, Object> test() throws InterruptedException, ExecutionException {
		long start = System.currentTimeMillis();

		Map<String, Object> map = new HashMap();
		List<Future<String>> futures = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			Future<String> future = testTwoService.hi(i);
			futures.add(future);
		}
		List<String> response = new ArrayList<>();
		for (Future future : futures) {
			String string = (String) future.get();
			response.add(string);
		}
		System.out.println(response);
		System.out.println("耗时"+(System.currentTimeMillis() - start)+"毫秒" );
		return map;
	}
}

service代码:

@Service
public class TestTwoService {
	@Async
	public Future<String> hi(int num) throws InterruptedException {
		Thread.sleep(5000);
		System.out.println("任务"+num +"执行完成!!");
		return new AsyncResult("任务"+num +"执行完成!!");
	}
}

运行结果:

5秒时

任务4执行完成!!
任务5执行完成!!
任务6执行完成!!
任务1执行完成!!
任务2执行完成!!
任务0执行完成!!
任务7执行完成!!

10秒时

任务3执行完成!!
任务8执行完成!!
任务9执行完成!!
[任务0执行完成!!, 任务1执行完成!!, 任务2执行完成!!, 任务3执行完成!!, 任务4执行完成!!, 任务5执行完成!!, 任务6执行完成!!, 任务7执行完成!!, 任务8执行完成!!, 任务9执行完成!!]
耗时10002毫秒

结果显示spring自带的异步任务线程数为7个(根据结果推测,不对请指正)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值