为了将线程池封装成一个通用的工具类,以便在所有RPC接口调用时复用,你可以创建一个工具类 RpcThreadPoolUtil。这个工具类将负责创建和管理线程池,并提供一个方法来异步执行RPC调用。
- 创建 RpcThreadPoolUtil 工具类
java
import java.util.concurrent.*;
public class RpcThreadPoolUtil {
private static final int CORE_POOL_SIZE = 10; // 核心线程数
private static final int MAXIMUM_POOL_SIZE = 20; // 最大线程数
private static final long KEEP_ALIVE_TIME = 60L; // 线程空闲时间
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // 时间单位
private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // 工作队列
private static final ExecutorService EXECUTOR;
static {
// 初始化线程池
EXECUTOR = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE,
KEEP_ALIVE_TIME,
TIME_UNIT,
WORK_QUEUE,
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("Rpc-Thread-Pool-Worker");
return t;
}
},
new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
);
}
/**
* 异步执行RPC调用
*
* @param callable RPC调用的Callable任务
* @param <T> 返回结果的类型
* @return CompletableFuture
*/
public static <T> CompletableFuture<T> executeAsync(Callable<T> callable) {
return CompletableFuture.supplyAsync(() -> {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}, EXECUTOR);
}
/**
* 关闭线程池
*/
public static void shutdown() {
EXECUTOR.shutdown();
}
/**
* 立即关闭线程池
*/
public static void shutdownNow() {
EXECUTOR.shutdownNow();
}
}
- 使用 RpcThreadPoolUtil 进行RPC调用
在你的业务逻辑中,可以使用 RpcThreadPoolUtil 来异步执行RPC调用。例如:
java
import java.util.LinkedHashMap;
import java.util.Objects;
import com.fasterxml.jackson.databind.ObjectMapper;
public class YourClass {
private final ObjectMapper objectMapper;
public YourClass() {
this.objectMapper = new ObjectMapper(); // 初始化 ObjectMapper
}
public void processVerification(OrderSignOffInput signOffInput, String hospitalSOID, VerifyOutput verifyOutput) {
// 使用 RpcThreadPoolUtil 异步调用 getFreeClass 方法
RpcThreadPoolUtil.executeAsync(() -> initializeVerifyService().getFreeClass(
signOffInput.getOrSignInput(),
hospitalSOID,
signOffInput.getDoctorId()
)).thenAccept(agreementMedicineVerifyOutputDTO -> {
if (agreementMedicineVerifyOutputDTO != null) {
verifyOutput.setVerifyActionId(13L);
verifyOutput.getSignVerifyResultList().add(this.createSignCommonVerifuResult(
13L,
objectMapper.convertValue(agreementMedicineVerifyOutputDTO, LinkedHashMap.class)
));
}
}).exceptionally(ex -> {
// 处理异常
ex.printStackTrace();
return null;
});
}
// 在适当的地方调用 shutdown 方法以关闭线程池
public void shutdown() {
RpcThreadPoolUtil.shutdown();
}
}