开放API请求工具类

一、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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值