Merge branch 'feature/REQ-1609' into dev

This commit is contained in:
TanJ 2023-11-17 15:04:36 +08:00
commit 9b5ac525be
2 changed files with 83 additions and 0 deletions

View File

@ -100,6 +100,10 @@
<groupId>org.aspectj</groupId> <groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId> <artifactId>aspectjrt</artifactId>
</dependency> </dependency>
<dependency>
<groupId>cn.axzo.framework</groupId>
<artifactId>axzo-common-domain</artifactId>
</dependency>
</dependencies> </dependencies>
<repositories> <repositories>

View File

@ -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 <R,T> T rpcProcessor(Supplier<R> 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,P> R rpcProcessorMayThrow(Supplier<P> supplier, String operationType, Consumer<Response<R>> throwConsumer, Object... param) {
Assert.notNull(throwConsumer,"自定义的异常处理不可为空");
log.info(operationType + "-Param: " + JSONUtil.toJsonStr(param));
Response<R> 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 <P,R> Response<R> printLatency(Supplier<P> function, String optType) {
StopWatch stopWatch = new StopWatch(optType);
stopWatch.start(optType);
Response<R> response = Response.create(JSONUtil.toJsonStr(function.get()));
stopWatch.stop();
log.info(stopWatch.shortSummary(TimeUnit.MILLISECONDS));
return response;
}
@Data
public static class Response<E> {
private Integer code;
private String msg;
private E data;
public static Response create(String data) {
return JSONUtil.toBean(data, Response.class);
}
}
}