java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot提高接口的响应速度

Springboot项目如何异步提高接口的响应速度

作者:钦拆大仁

这篇文章主要介绍了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<Long> 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<Long> 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<Long> 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<Long> task1 = task.doTaskOne();
		Future<Long> task2 = task.doTaskTwo();
		Future<Long> 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) + "毫秒");
	}

}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文