Springboot项目如何异步提高接口的响应速度
更新时间:2025年06月25日 08:45:29 作者:钦拆大仁
这篇文章主要介绍了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) + "毫秒");
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
java(Java 25 LTS)的下载、安装、配置图文教程 (IDEA 2025 为例)
在Java开发中选择合适的JDK版本至关,重要这篇文章主要介绍了java(Java 25 LTS)的下载、安装、配置的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下2025-11-11
spring boot使用logback日志级别打印控制操作
这篇文章主要介绍了spring boot使用logback日志级别打印控制操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-03-03
Spring AI借助全局参数实现智能数据库操作与个性化待办管理
这篇文章主要介绍了Spring AI借助全局参数实现智能数据库操作与个性化待办管理,本文给大家介绍的非常详细,需要的朋友可以参考下2024-11-11
SpringCloud集成Micrometer Tracing的代码工程
Micrometer Tracing 是一个用于微服务架构的追踪库,它提供了一种简单而强大的方式来收集和报告分布式系统中的性能和调用链信息,Micrometer Tracing 旨在帮助开发者和运维人员理解微服务之间的交互,本文给大家介绍了如何在 Spring Cloud 集成 Micrometer Tracing2024-12-12


最新评论