为了将线程池封装成一个通用的工具类,以便在所有RPC接口调用时复用,你可以创建一个工具类 RpcThreadPoolUtil。这个工具类将负责创建和管理线程池,并提供一个方法来异步执行RPC调用。
- 创建 RpcThreadPoolUtil 工具类
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() {@Overridepublic Thread newThread(Runnable r) {Thread t = new Thread(r);t.setName("Rpc-Thread-Pool-Worker");return t;}},new ThreadPoolExecutor.AbortPolicy() );}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调用。例如:
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(); }public void processVerification(OrderSignOffInput signOffInput, String hospitalSOID, VerifyOutput verifyOutput) {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;});}public void shutdown() {RpcThreadPoolUtil.shutdown();}
}