From 0ac90baba2dc5b3731e8919fc1df22e5a2c60033 Mon Sep 17 00:00:00 2001 From: TanJ Date: Fri, 17 Nov 2023 15:04:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(1609):=20=E7=BB=9F=E4=B8=80response?= =?UTF-8?q?=E5=B0=81=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 4 + .../java/cn/axzo/pokonyan/util/RpcUtil.java | 79 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/main/java/cn/axzo/pokonyan/util/RpcUtil.java diff --git a/pom.xml b/pom.xml index 95016da..d355fbd 100644 --- a/pom.xml +++ b/pom.xml @@ -100,6 +100,10 @@ org.aspectj aspectjrt + + cn.axzo.framework + axzo-common-domain + diff --git a/src/main/java/cn/axzo/pokonyan/util/RpcUtil.java b/src/main/java/cn/axzo/pokonyan/util/RpcUtil.java new file mode 100644 index 0000000..d6fa9a0 --- /dev/null +++ b/src/main/java/cn/axzo/pokonyan/util/RpcUtil.java @@ -0,0 +1,79 @@ +package cn.axzo.pokonyan.util; + + +import cn.axzo.framework.domain.ServiceException; +import cn.hutool.core.date.StopWatch; +import cn.hutool.core.lang.Assert; +import cn.hutool.http.HttpStatus; +import cn.hutool.json.JSONUtil; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * 外部rpc接口 返回 CommonResponse + * @author tanjie@axzo.cn + * @date 2022/5/23 11:08 + */ +@Slf4j +public class RpcUtil { + + /** + * 常用的RPC请求返回值解析,如果 被请求方 返回非200会抛出异常 + * + */ + public static T rpcProcessor(Supplier supplier, String operationType, Object... param) { + + return rpcProcessorMayThrow(supplier, operationType, commonResponse -> { + throw new ServiceException(commonResponse.getMsg()); + }, param); + } + + + /** + * 第三方发生异常时,自定义处理逻辑 + * + * @param supplier + * @param operationType + * @param throwConsumer + * @param param + * @return + */ + public static R rpcProcessorMayThrow(Supplier

supplier, String operationType, Consumer> throwConsumer, Object... param) { + Assert.notNull(throwConsumer,"自定义的异常处理不可为空"); + log.info(operationType + "-Param: " + JSONUtil.toJsonStr(param)); + Response response = printLatency(supplier, operationType); + log.info(operationType + "-Result: " + JSONUtil.toJsonStr(response)); + + Assert.notNull(response, "服务调用异常"); + // 200自定义处理 + if (HttpStatus.HTTP_OK != response.getCode()) { + throwConsumer.accept(response); + } + return response.getData(); + } + public static Response printLatency(Supplier

function, String optType) { + StopWatch stopWatch = new StopWatch(optType); + stopWatch.start(optType); + Response response = Response.create(JSONUtil.toJsonStr(function.get())); + stopWatch.stop(); + log.info(stopWatch.shortSummary(TimeUnit.MILLISECONDS)); + return response; + } + + + @Data + public static class Response { + private Integer code; + private String msg; + private E data; + + public static Response create(String data) { + return JSONUtil.toBean(data, Response.class); + } + } + +}