SpringBoot实现异步调用


在Java中使用Spring Boot实现异步请求和异步调用是一个常见的需求,可以提高应用程序的性能和响应能力。以下是实现这两种异步操作的基本方法:


1. 异步请求(Asynchronous Request)
异步请求允许客户端发送请求后立即返回,而不需要等待服务器处理完成。
示例代码:

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
@RequestMapping("/async")
public class AsyncController {
    
    /**
     * 使用 DeferredResult 实现异步请求
     * @return
     */
    @GetMapping("/deferred")
    public DeferredResult<String> deferredAsyncRequest() {
        DeferredResult<String> deferredResult = new DeferredResult<>();
        // 模拟异步处理
        new Thread(() -> {
            try {
                Thread.sleep(5000); // 模拟耗时操作
                deferredResult.setResult("Async request deferred");
            } catch (InterruptedException e) {
                deferredResult.setErrorResult(e);
            }
        }).start();
        return deferredResult;
    }
    
    /**
     * 使用 Callable 实现异步请求
     * @return
     */
    @GetMapping("/callable")
    public Callable<String> callableAsyncRequest() {
        return () -> {
            Thread.sleep(5000); // 模拟耗时操作
            return "Async request callable";
        };
    }
    
    /**
     * 使用 CompletableFuture 实现异步请求
     * @return
     */
    @GetMapping("/completable")
    public CompletableFuture<String> completableAsyncRequest() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Async request completed";
        });
    }
}

2. 异步调用(Asynchronous Method Invocation)


异步调用允许在服务端异步执行方法,不阻塞主线程。Spring Boot使用`@Async`注解来实现这一功能。


首先,在主应用类上启用异步支持:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

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

在使用 @Async 之前,我们需要配置一个线程池(Executor),定义一个TaskExecutor Bean,以便异步方法能够在独立的线程中执行

import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Async-");
        executor.initialize();
        return executor;
    }
}

线程池配置建议

  • CPU 密集型任务:建议核心线程数为 CPU 核心数的 n 倍,最大线程数为核心线程数的 2 倍。

  • IO 密集型任务:建议核心线程数设置为较大的值,最大线程数可以为核心线程数的 2 倍甚至更多。

合理配置线程池可以避免线程饥饿和死锁等问题,提升系统的吞吐量。

然后,创建一个服务类来执行异步操作:

import java.util.concurrent.CompletableFuture;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService{
    /**
     * 异步方法
     * @return
     */
    @Async("taskExecutor")
    public CompletableFuture<String> async(){
        try {
            Thread.sleep(5000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return CompletableFuture.completedFuture("Async method completed");
    }
}


最后,在控制器中使用异步服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;

@RestController

@RequestMapping("/async")
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/async-call")
    public CompletableFuture<String> asyncCall() {
        return asyncService.async();
    }
}

什么时候使用异步请求

异步请求在以下情况下特别有用:

  • 长时间运行的任务:例如文件上传、复杂计算、大量数据处理等。

  • I/O操作:例如数据库查询、调用外部API、文件读写等。

  • 资源密集型任务:例如图像处理、视频编码等。

总结:

这些示例展示了如何在Spring Boot中实现异步请求和异步调用。Spring Boot提供了`@Async`注解和`DeferredResult`、`Callable`、`CompletableFuture`来实现这一功能,提高了应用程序的并发处理能力,开发者可以根据不同的需求选择合适的异步处理方式。

合理配置线程池,以确保最佳性能和资源利用,正确处理异步任务中的异常,以及在合适的场景中应用异步处理技术,是开发高性能应用的关键。

个人观点,仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值