闽公网安备 35020302035485号
异步调用:是指在服务器内部,某个方法调用无需等待其他方法完成即可继续执行。通常用于需要耗时较长的任务,以避免阻塞主线程。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig {
// 堆代码 duidaima.com
@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;
}
}
4.2 在方法上使用 @Asyncimport org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
@Service
public class AsyncService {
@Async("taskExecutor")
public CompletableFuture<String> asyncMethod() throws InterruptedException {
Thread.sleep(2000); // 模拟长时间的任务
return CompletableFuture.completedFuture("任务完成");
}
}
4.3 异步异常处理 @Async("taskExecutor")
public CompletableFuture<String> asyncMethodWithException() {
return CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("模拟异常");
}
return "任务完成";
}).exceptionally(ex -> {
// 异常处理
return "任务失败:" + ex.getMessage();
});
}
4.4 线程池配置建议import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Callable;
@RestController
public class CallableController {
@GetMapping("/callable")
public Callable<String> processAsyncRequest() {
return () -> {
Thread.sleep(2000); // 模拟长时间的任务
return "处理完成";
};
}
}
5.2 使用 DeferredResult 实现异步请求import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.ForkJoinPool;
@RestController
public class DeferredResultController {
@GetMapping("/deferred")
public DeferredResult<String> processDeferredRequest() {
DeferredResult<String> output = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
try {
Thread.sleep(2000); // 模拟长时间的任务
output.setResult("处理完成");
} catch (InterruptedException e) {
output.setErrorResult(e.getMessage());
}
});
return output;
}
}
5.3 使用 CompletableFuture 实现异步请求import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@RestController
public class CompletableFutureController {
@GetMapping("/completable")
public CompletableFuture<String> processCompletableRequest() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000); // 模拟长时间的任务
} catch (InterruptedException e) {
e.printStackTrace();
}
return "处理完成";
});
}
}
结语