登录
首页 >  文章 >  前端

Spring中实现异步调用教程详解

时间:2025-12-04 14:37:53 270浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

积累知识,胜过积蓄金银!毕竟在文章开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《JS如何在Spring中实现异步调用教程》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

前端JavaScript通过fetch或axios发起异步请求,调用Spring Boot后端接口;Spring使用@EnableAsync启用异步支持,@Async注解实现异步方法,配合DeferredResult非阻塞返回结果,提升系统响应能力。

JS怎样在Spring中实现异步调用_JS在Spring中实现异步调用的完整教程

JavaScript 本身是前端语言,而 Spring 是基于 Java 的后端框架,因此“JS 在 Spring 中实现异步调用”这个说法需要澄清:通常是指前端 JavaScript 发起异步请求(如 AJAX),调用 Spring 后端提供的异步接口。下面将从前后端配合的角度,完整说明如何实现这一过程。

前端:使用 JS 发起异步请求

前端通过 JavaScript(或现代框架如 Vue、React)发送异步 HTTP 请求到 Spring 服务。常用方式包括原生 fetchaxios 库。

示例:使用 fetch 发起 GET 请求

fetch('/api/data', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
示例:使用 axios 发送 POST 请求

axios.post('/api/data', { name: 'test' })
  .then(response => {
    console.log('Success:', response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

这些请求默认就是异步的,不会阻塞页面渲染。

后端:Spring Boot 实现异步处理

为了让 Spring 接口支持真正的异步执行(即不占用主线程),需使用 Spring 的 @Async 注解。

1. 启用异步支持

在主启动类上添加 @EnableAsync

@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
2. 创建异步服务方法

定义一个服务类,使用 @Async 标记方法:

@Service
public class AsyncService {

    @Async
    public CompletableFuture<string> doSomething() {
        try {
            Thread.sleep(3000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return CompletableFuture.completedFuture("Task Done");
    }
}
</string>
3. 控制器返回异步结果

Controller 接收请求并调用异步服务:

@RestController
@RequestMapping("/api")
public class DataController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/data")
    public DeferredResult<string> getData() {
        DeferredResult<string> result = new DeferredResult();

        asyncService.doSomething().whenComplete((data, ex) -> {
            if (ex != null) {
                result.setErrorResult(ex);
            } else {
                result.setResult(data);
            }
        });

        return result;
    }
}
</string></string>

这里使用 DeferredResult 可以让 Controller 异步返回结果,避免阻塞请求线程。

跨域问题处理

前端 JS 与 Spring 后端常处于不同端口,需配置跨域访问权限。

在 Controller 上添加 @CrossOrigin

@CrossOrigin(origins = "http://localhost:3000") // 允许前端域名
@RestController
public class DataController { ... }
或全局配置跨域

@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://localhost:3000")
                        .allowedMethods("GET", "POST", "PUT", "DELETE");
            }
        };
    }
}

测试流程

假设前端运行在 http://localhost:3000,后端在 http://localhost:8080

  • 前端页面加载后,执行 JS 脚本发起 fetch 请求
  • Sprong Boot 接收到请求,交由异步服务处理
  • 主线程不被阻塞,可处理其他请求
  • 异步任务完成后,结果返回给前端,触发 then 回调

基本上就这些。整个链路实现了 JS 发起异步调用,Spring 完成异步处理,提升系统响应能力。关键点在于前后端分离架构下,正确使用异步注解和非阻塞返回机制。

到这里,我们也就讲完了《Spring中实现异步调用教程详解》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于JavaScript,Spring,@async,异步调用,DeferredResult的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>