Skip to content

Commit

Permalink
Merge pull request #12 from adorabled4/feature/call-async
Browse files Browse the repository at this point in the history
新增支持异步接口调用
  • Loading branch information
adorabled4 authored Jan 2, 2024
2 parents a5d95ac + a118e63 commit 0acf622
Show file tree
Hide file tree
Showing 39 changed files with 607 additions and 154 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.dhx.apicommon.common.exception.ErrorCode;
import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

Expand All @@ -13,18 +14,22 @@
@Data
public class BaseResponse<T> implements Serializable {

public static final String TRACE_ID = "traceId";

private static final long serialVersionUID = 1L;
private int code;

private T data;// controller 中的不同的方法返回值的类型不同

private String message;

private String traceId;

public BaseResponse(int code, T data, String message) {
this.code = code;
this.data = data;
this.message = message;
this.traceId= MDC.get(TRACE_ID);
}

public BaseResponse(ErrorCode errorCode) {
Expand Down
13 changes: 13 additions & 0 deletions api-common/src/main/java/com/dhx/apicommon/common/MQConstant.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.dhx.apicommon.common;

/**
* @author adorabled4
* @className MQConstant
* @date : 2024/01/02/ 09:22
**/
public class MQConstant {

public static final String CALL_BACK_RESULT_EXCHANGE = "TurboAPI-call-back";

public static final String CALL_RESULT_QUEUE = "call.result";
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ public class InterfaceTo implements Serializable {
*/
private Long totalCallCount;

/**
* 是否是异步接口
*/
private boolean isAsync;


private static final long serialVersionUID = 1L;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.dhx.apicommon.model.v2.param;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;


/**
* @author adorabled4
* @className TranslateParam
* @date : 2024-1-2 07:58:12
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TranslateParam {

/**
* 菜品
*/
@Length(min = 1,max = 3600)
private String text;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,13 @@ public interface InnerInterfaceService {
* @return
*/
InterfaceTo getInterfaceInfo(String callPath , String method);

/**
* 校验回调接口配置
*
* @param userId 用户id
* @param interfaceId interfaceId
* @return boolean
*/
boolean checkCallBackConfig(Long userId, Long interfaceId);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.dhx.apicommon.service;

import com.dhx.apicommon.common.BaseResponse;
import com.dhx.apicommon.model.to.InterfaceTo;

/**
* @author adorabled4
Expand All @@ -16,5 +17,13 @@ public interface InnerUserInterfaceInfoService {
* @param interfaceId 接口id
* @return boolean
*/
boolean invokeCount(Long userId, Long interfaceId, Integer cost);
boolean invokeCount(Long userId, Long interfaceId, Integer cost,boolean isSuccess);

/**
* 预先创建调用上下文信息
*
* @param interfaceTo 接口
* @param userId 用户id
*/
void createCallResult(InterfaceTo interfaceTo,Long userId);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.dhx.apicore.util;
package com.dhx.apicommon.util;


import com.dhx.apicommon.common.exception.BusinessException;
Expand Down
4 changes: 4 additions & 0 deletions api-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.dhx.apicore.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhx.apicommon.common.BaseResponse;
import com.dhx.apicommon.util.ResultUtil;
import com.dhx.apicore.model.DO.CallBack;
import com.dhx.apicore.model.query.AddCalLBackQuery;
import com.dhx.apicore.model.query.PageQuery;
import com.dhx.apicore.service.CallBackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
* @author adorabled4
* @className CallbackController
* @date : 2024/01/02/ 00:07
**/
@RestController
@Api(value = "回调配置")
public class CallbackController {

@Resource
CallBackService callBackService;

@PostMapping("/config/add")
@ApiOperation(value = "添加接口回调地址配置")
public BaseResponse<String> addCallBackConfig(AddCalLBackQuery query){
callBackService.addCallBackConfig(query);
return ResultUtil.success("");
}


@GetMapping("/config/delete")
@ApiOperation(value = "删除接口回调地址配置")
public BaseResponse<String> delCallBackConfig(@RequestParam("id")Long id){
callBackService.removeById(id);
return ResultUtil.success("删除成功!");
}

@GetMapping("/config/list")
@ApiOperation(value = "查询接口回调地址配置")
public BaseResponse<Page<CallBack>> listCallBackConfig(PageQuery query){
return ResultUtil.success(callBackService.listConfigs(query));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import com.dhx.apicore.model.query.UserUpdateQuery;
import com.dhx.apicore.model.vo.UserVo;
import com.dhx.apicore.service.UserService;
import com.dhx.apicore.util.ThrowUtil;
import com.dhx.apicommon.util.ThrowUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.dhx.apicore.listener;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.dhx.apicommon.common.MQConstant;
import com.dhx.apicommon.common.exception.BusinessException;
import com.dhx.apicommon.common.exception.ErrorCode;
import com.dhx.apicore.model.DO.CallBack;
import com.dhx.apicore.model.DO.CallResult;
import com.dhx.apicore.model.enums.CallApiStatusEnum;
import com.dhx.apicore.service.CallBackService;
import com.dhx.apicore.service.CallResultService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.representer.BaseRepresenter;

import javax.annotation.Resource;

import java.io.IOException;

import static com.dhx.apicommon.common.BaseResponse.TRACE_ID;

/**
* @author adorabled4
* @className CallResultListener
* @date : 2024/01/02/ 09:26
**/
@Component
@Slf4j
public class CallResultListener {

@Resource
CallResultService callResultService;

@Resource
CallBackService callBackService;

/**
* 接收异步接口执行结果
*/
@RabbitListener(bindings = @QueueBinding(value = @Queue(name = MQConstant.CALL_RESULT_QUEUE),
exchange = @Exchange(name = MQConstant.CALL_BACK_RESULT_EXCHANGE, type = ExchangeTypes.DIRECT),
key = MQConstant.CALL_RESULT_QUEUE))
public void callResultSendListener(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag) throws IOException {
String traceId = MDC.get(TRACE_ID);
try{
log.info("receive message :{}", message);
if (StringUtils.isBlank(message)) {
channel.basicNack(deliverTag, false, false);
throw new BusinessException(ErrorCode.PARAMS_ERROR, "接收到的消息为空!");
}
// 查询config
BaseRepresenter invokeResult = JSONUtil.toBean(message, BaseRepresenter.class);
CallResult callResult = callResultService.findByTraceId(traceId);
CallBack callBack = callBackService.findCallBackConfig(callResult.getInterfaceId(),callResult.getUserId());
String callBackUrl = callBack.getCallBackUrl();
// 发送结果
HttpRequest.post(callBackUrl).body(invokeResult.toString()).executeAsync();
// 更新调用状态
callResultService.updateCallStatus(traceId, CallApiStatusEnum.SUCCEED);
}catch (Exception e){
callResultService.updateCallStatus(traceId, CallApiStatusEnum.FAILED);
}
}


}
26 changes: 18 additions & 8 deletions api-core/src/main/java/com/dhx/apicore/model/DO/CallBack.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,20 @@
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.time.LocalDateTime;

import com.dhx.apicore.model.query.AddCalLBackQuery;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
*
* @TableName call_back
*/
@TableName(value ="call_back")
@TableName(value = "call_back")
@Data
@NoArgsConstructor
public class CallBack implements Serializable {
/**
* 主键, 自增
Expand Down Expand Up @@ -60,6 +64,12 @@ public class CallBack implements Serializable {
@TableField(exist = false)
private static final long serialVersionUID = 1L;

public CallBack(AddCalLBackQuery query) {
this.callBackUrl = query.getCallBackUrl();
this.interfaceId = query.getInterfaceId();
this.createTime = LocalDateTime.now();
}

@Override
public boolean equals(Object that) {
if (this == that) {
Expand All @@ -73,12 +83,12 @@ public boolean equals(Object that) {
}
CallBack other = (CallBack) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getInterfaceId() == null ? other.getInterfaceId() == null : this.getInterfaceId().equals(other.getInterfaceId()))
&& (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
&& (this.getCallBackUrl() == null ? other.getCallBackUrl() == null : this.getCallBackUrl().equals(other.getCallBackUrl()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getUpdateTime() == null ? other.getUpdateTime() == null : this.getUpdateTime().equals(other.getUpdateTime()))
&& (this.getIsDelete() == null ? other.getIsDelete() == null : this.getIsDelete().equals(other.getIsDelete()));
&& (this.getInterfaceId() == null ? other.getInterfaceId() == null : this.getInterfaceId().equals(other.getInterfaceId()))
&& (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
&& (this.getCallBackUrl() == null ? other.getCallBackUrl() == null : this.getCallBackUrl().equals(other.getCallBackUrl()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getUpdateTime() == null ? other.getUpdateTime() == null : this.getUpdateTime().equals(other.getUpdateTime()))
&& (this.getIsDelete() == null ? other.getIsDelete() == null : this.getIsDelete().equals(other.getIsDelete()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;

import com.dhx.apicore.model.enums.CallApiStatusEnum;
import lombok.Data;

/**
Expand Down Expand Up @@ -49,7 +51,7 @@ public class CallResult implements Serializable {
* 本次调用执行状态
*/
@TableField(value = "status")
private Integer status;
private CallApiStatusEnum status;

/**
* 创建时间
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ public class InterfaceInfoEntity implements Serializable {
*/
private LocalDateTime updateTime;

/**
* 是否是异步API
*/
private Boolean isAsync;

/**
* 逻辑删除字段
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,5 +111,10 @@ public class InterfaceMetaDataDTO implements Serializable {
*/
private String modelName;

/**
* 是否是异步接口
*/
private String isAsync;

private static final long serialVersionUID = 1L;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.dhx.apicore.model.query;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.Pattern;

/**
* @author adorabled4
* @className AddCalLBackQuery
* @date : 2024/01/02/ 00:08
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AddCalLBackQuery {

@Pattern(regexp ="^(http|https)://.*$", message = "非法的回调消息接收地址!")
private String callBackUrl;

private Long interfaceId;

}
Loading

0 comments on commit 0acf622

Please sign in to comment.