栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot项目时候异步提高接口的响应速度

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot项目时候异步提高接口的响应速度


asynchronous CALL(异步调用)一个可以无需等待被调用函数的返回值就让操作继续进行的方法

1、启动类上添加开启异步注解

@EnableAsync
public class Application {

 2、编写异步方法

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

@Component
public class Task {

	public static Random random =new Random();

	@Async
	public Future doTaskOne() throws Exception {
		System.out.println("开始做任务一");
		long start = System.currentTimeMillis();
		Thread.sleep(random.nextInt(10000));
		long end = System.currentTimeMillis();
		return new AsyncResult<>(end-start);
	}
	@Async
	public Future doTaskTwo() throws Exception {
		System.out.println("开始做任务二");
		long start = System.currentTimeMillis();
		Thread.sleep(random.nextInt(10000));
		long end = System.currentTimeMillis();
		return new AsyncResult<>(end-start);
	}
	@Async
	public Future doTaskThree() throws Exception {
		System.out.println("开始做任务三");
		long start = System.currentTimeMillis();
		Thread.sleep(random.nextInt(10000));
		long end = System.currentTimeMillis();
		return new AsyncResult<>(end-start);
	}
}

3、执行异步调用

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=Application.class)
public class MainTester {

	@Resource
	private Task task;

	@Test
	public void test() throws Exception {
		long start = System.currentTimeMillis();

		Future task1 = task.doTaskOne();
		Future task2 = task.doTaskTwo();
		Future task3 = task.doTaskThree();
		Long res1 = task1.get();
		Long res2 = task2.get();
		Long res3 = task3.get();
		System.out.println("任务1完成耗时:"+res1);
		System.out.println("任务2完成耗时:"+res2);
		System.out.println("任务3完成耗时:"+res3);
		long end = System.currentTimeMillis();

		System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
	}

}

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/390273.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号