一、API请求工具类
package com.dst.lcb.base.common.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.dst.steed.common.domain.response.Response;
import com.dst.steed.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
/**
* 开放API请求工具类
* lwp
* 2024-03-01
*/
@Slf4j
public class OpenApiUtil {
/**
* 服务间调用
* 会对异常返回结果进行判断,不对外抛异常
*
* @param name 名称
* @param t 入参
* @return Results
*/
public static <T, V> Response<V> execApi(String name, T t, OpenApiPredicate<T, V> predicate) {
Response<V> results = new Response<>();
try {
results = execApiThrowException(name, t, predicate);
} catch (BusinessException e) {
log.error("服务调用异常:" + e);
}
return results;
}
/**
* 服务间调用
* 会对异常返回结果进行判断,如果不成功或无返回值则会抛出异常
*
* @param name 名称
* @param t 入参
* @return Results
*/
public static <T, V> Response<V> execApiThrowException(String name, T t, OpenApiPredicate<T, V> predicate) {
Response<V> results;
Date s = new Date();
try {
log.info("请求地上铁内部服务【{}】入参:{}", name, JSON.toJSONString(t));
results = predicate.request(t);
} catch (Exception e) {
log.error("服务调用异常:" + e);
throw new BusinessException("服务异常,请稍后再试!");
}
log.info("请求地上铁内部服务【{}】耗时:{},返回: {}", name, DateUtil.formatBetween(s, new Date()), JSON.toJSONString(results));
if (ObjectUtil.isEmpty(results)) {
log.error("服务调用异常:【{}】", results);
throw new BusinessException("服务异常,请稍后再试!");
}
if (!results.isSuccess()) {
log.error("请求地上铁内部服务返回失败,服务名:【{}】,返回结果【{}】", name, JSONUtil.toJsonStr(results));
throw new BusinessException("服务异常,请稍后再试!");
}
return results;
}
}
二、openApi函数接口
package com.dst.lcb.base.common.utils;
import com.dst.steed.common.domain.response.Response;
/**
* openApi函数接口
*/
public interface OpenApiPredicate<T, V> {
Response<V> request(T t);
}
三、使用工具类
//查询交易,获取待支付账单
SmallBcLeasePayDetailParam smallBcLeasePayDetailParam = new SmallBcLeasePayDetailParam();
smallBcLeasePayDetailParam.setParentOrderCodeList(param.getParentOrderCodeList());
Response<SmallBcPayDetailResponse> payDetailResult = OpenApiUtil.execApiThrowException("查询交易,获取待支付账单", smallBcLeasePayDetailParam, remoteTradeApi::getPayDetail);
SmallBcPayDetailResponse payDetail = payDetailResult.getData();