在java中使用spring boot实现异步请求和异步调用是一个常见的需求,可以提高应用程序的性能和响应能力。以下是实现这两种异步操作的基本方法:
一、异步请求(asynchronous request)
异步请求允许客户端发送请求后立即返回,而不需要等待服务器处理完成,异步调用允许在服务端异步执行方法,不阻塞主线程。
二、在 spring boot 中,实现异步调用主要有以下几种方法:
1. 使用 @async 注解
步骤:
- 启用异步支持:在主类上添加
@enableasync。 - 定义异步方法:在需要异步执行的方法上使用
@async注解。 - 自定义线程池(可选):提高异步任务的线程管理效率,以便异步方法能够在独立的线程中执行
示例代码:
主类:
package com.work;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.scheduling.annotation.enableasync;
@springbootapplication(scanbasepackages = {"com.work.*"})
@enableasync
//@enablescheduling
public class springbootworkapplication {
public static void main(string[] args) {
springapplication.run(springbootworkapplication.class, args);
}
}异步方法:
package com.work.service;
import org.springframework.scheduling.annotation.async;
import org.springframework.stereotype.service;
import lombok.extern.slf4j.slf4j;
/**
* 异步调用service
* @author summer
*/
@service
@slf4j
public class asyncservice {
/**
* 使用 @async 注解 实现异步调用
* taskexecutor为自定义线程池,指定自定义线程池
* @return
* @throws interruptedexception
*/
@async("taskexecutor")
public void async(){
log.info("async异步任务开始: " + thread.currentthread().getname());
try {
// 模拟耗时操作(实际工作中,此处写业务逻辑处理)
thread.sleep(30000);
} catch (interruptedexception e) {
e.printstacktrace();
}
log.info("async异步任务完成");
}
}自定义线程池(可选):
package com.work.config;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.core.task.taskexecutor;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
/**
* 自定义异步线程执行线程池
* @author summer
*
*/
@configuration
public class executorconfig {
@bean(name = "taskexecutor")
public taskexecutor taskexecutor() {
threadpooltaskexecutor executor = new threadpooltaskexecutor();
executor.setcorepoolsize(5);
executor.setmaxpoolsize(10);
executor.setqueuecapacity(50);
executor.setthreadnameprefix("taskexecutor-");
executor.initialize();
return executor;
}
}
在 @async("taskexecutor") 中指定自定义线程池。
调用:
package com.work.controller;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import com.work.common.result.commonresult;
import com.work.service.asyncservice;
import lombok.extern.slf4j.slf4j;
/**
* 测试异步执行controller
* @author summer
*
*/
@restcontroller
@requestmapping("/async")
@slf4j
public class asynctestcontroller {
@autowired
private asyncservice asyncservice;
@getmapping("/async")
public commonresult<string> async() {
asyncservice.async();
log.info("async异步任务调用成功");
return commonresult.success("async异步任务调用成功");
}
}异步方法休眠30秒,可以看到控制台打印的日志

线程池配置建议
- cpu 密集型任务:建议核心线程数为 cpu 核心数的
n倍,最大线程数为核心线程数的 2 倍。 - io 密集型任务:建议核心线程数设置为较大的值,最大线程数可以为核心线程数的 2 倍甚至更多。
合理配置线程池可以避免线程饥饿和死锁等问题,提升系统的吞吐量。
2. 使用 java 原生线程池
spring 提供线程池,但可以直接使用 java 原生的线程池来实现异步。
示例代码:
package com.work.service;
import java.util.concurrent.linkedblockingqueue;
import java.util.concurrent.threadpoolexecutor;
import java.util.concurrent.timeunit;
import org.springframework.stereotype.service;
import lombok.extern.slf4j.slf4j;
/**
* 异步调用service
* @author summer
*
*/
@service
@slf4j
public class asyncservice{
/**
* 使用 java 原生线程池来实现异步调用
*/
public void asyncthreadpool() {
threadpoolexecutor pool=new threadpoolexecutor(5, 10,
2, timeunit.seconds, new linkedblockingqueue<runnable>(100),new threadpoolexecutor.callerrunspolicy());
pool.execute(() -> {
log.info("asyncthreadpool异步任务开始: " + thread.currentthread().getname());
try {
// 模拟耗时操作(实际工作中,此处写业务逻辑处理)
thread.sleep(30000);
} catch (interruptedexception e) {
e.printstacktrace();
}
log.info("asyncthreadpool异步任务完成");
});
}
}
调用:
package com.work.controller;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import com.work.common.result.commonresult;
import com.work.service.asyncservice;
import lombok.extern.slf4j.slf4j;
/**
* 测试异步执行controller
* @author summer
*
*/
@restcontroller
@requestmapping("/async")
@slf4j
public class asynctestcontroller {
@autowired
private asyncservice asyncservice;
@getmapping("/asyncthreadpool")
public commonresult<string> asyncthreadpool() {
asyncservice.asyncthreadpool();
log.info("asyncthreadpool异步任务调用成功");
return commonresult.success("asyncthreadpool异步任务调用成功");
}
}
异步方法休眠30秒,可以看到控制台打印的日志

3. 使用 spring 的 taskexecutor
taskexecutor 是 spring 提供的抽象接口,适合用来执行异步任务。
配置 taskexecutor:
package com.work.config;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.core.task.taskexecutor;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
/**
* 自定义异步线程执行线程池
* @author summer
*
*/
@configuration
public class executorconfig {
@bean(name = "taskexecutor")
public taskexecutor taskexecutor() {
threadpooltaskexecutor executor = new threadpooltaskexecutor();
executor.setcorepoolsize(5);
executor.setmaxpoolsize(10);
executor.setqueuecapacity(50);
executor.setthreadnameprefix("taskexecutor-");
executor.initialize();
return executor;
}
}示例代码:
package com.work.service;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.core.task.taskexecutor;
import org.springframework.stereotype.service;
import lombok.extern.slf4j.slf4j;
/**
* 异步调用service
* @author summer
*
*/
@service
@slf4j
public class asyncservice{
@autowired
private taskexecutor taskexecutor;
/**
* 使用 spring 的 taskexecutor 来实现异步调用
*/
public void asyncexecutor() {
taskexecutor.execute(() -> {
log.info("asyncexecutor异步任务开始:" + thread.currentthread().getname());
try {
// 模拟耗时操作(实际工作中,此处写业务逻辑处理)
thread.sleep(30000);
} catch (interruptedexception e) {
e.printstacktrace();
}
log.info("asyncexecutor异步任务完成");
});
}
}
调用:
package com.work.controller;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import com.work.common.result.commonresult;
import com.work.service.asyncservice;
import lombok.extern.slf4j.slf4j;
/**
* 测试异步执行controller
* @author summer
*
*/
@restcontroller
@requestmapping("/async")
@slf4j
public class asynctestcontroller {
@autowired
private asyncservice asyncservice;
@getmapping("/asyncexecutor")
public commonresult<string> asyncexecutor() {
asyncservice.asyncexecutor();
log.info("asyncexecutor异步任务调用成功");
return commonresult.success("asyncexecutor异步任务调用成功");
}
}
异步方法休眠30秒,可以看到控制台打印的日志

三、什么时候使用异步请求
异步请求在以下情况下特别有用:
- 长时间运行的任务:例如文件上传、复杂计算、大量数据处理等。
- i/o操作:例如数据库查询、调用外部api、文件读写等。
- 资源密集型任务:例如图像处理、视频编码等。
四、总结
方法 | 优点 | 缺点 |
@async 注解 | 简单易用,与 spring 集成良好 | 需要 spring 容器管理的 bean 才能生效 |
executorservice | 更底层、更灵活 | 手动管理线程池 |
taskexecutor | spring 提供的抽象,方便扩展 | 配置稍显复杂 |
这些示例展示了如何在spring boot中实现异步请求和异步调用。spring boot提供了`@async`注解和`java原生线程池`、`taskexecutor`来实现这一功能,提高了应用程序的并发处理能力,开发者可以根据不同的需求选择合适的异步处理方式。
合理配置线程池,以确保最佳性能和资源利用,正确处理异步任务中的异常,以及在合适的场景中应用异步处理技术,是开发高性能应用的关键。
到此这篇关于springboot实现异步调用的方法示例的文章就介绍到这了,更多相关springboot 异步调用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论