跳转到内容

原生接口开发指南

  1. 在对接第三方支付, 或者一些其他特殊场景, 会有一些回调的请求, 但是回调的格式是第三方定义的, 无法适配 Trantor 的机制规范, 所以使用 LogicFlow 和 LogicFunction 基本无法满足此类场景。
  2. Trantor 考虑增加原生的 RestAPI 支持, 可以通过注解的方式来声明对应的 Rest API, 以满足特殊的回调请求。 因为是原生的基本 Rest API, 所以暴露最基本的请求方式即可, 入参使用 Request/Response , 允许声明 Path 和 Method。 Path 支持 PathVariables 的方式,并有对应的工具获取参数。

常规使用

使用步骤:

  1. 定义一个类,实现 RestAPI 接口
  2. 加上 RestApi 注解,写上支持 pathmethod
  3. 该 RestApi 可以引入其他 LogicFlow 和 LogicFunc
@RestApi(path = "/test/normal", method= RestApiMethod.GET)
public class NormalRestApi implements RestAPI {
@Autowired
private CreateItemFunc createItemFunc;
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) {
ItemBO item = new ItemBO();
item.setItemName("this is name");
item.setDesc("this is desc");
createItemFunc.execute(item);
}
}

之后重启服务,通过 postman 或浏览器以 Get 的方式 访问 /test/normal, 便可以触发该原生接口。

使用 path variable

  1. path 支持 {} , 用于路径匹配;
  2. 提供了 RestApiUtils 获取相关的匹配值;
@RestApi(path = "/test/{name}/{age}", method = RestApiMethod.GET)
public class PathGetRestApi implements RestAPI {
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) {
Map<String, String> pathMap = RestApiUtils.extractPathValue(req);
System.out.println(pathMap);
}
}

定义异常处理

Trantor 默认提供的异常处理器将错误信息转为 Response,如需自定义当前模块的全局默认异常处理器,可以实现 RestApiErrorHandler 这个接口, 并注入 IOC 容器中。

如果不需要全局处理,可以自己 try..catch.. 转为对应的错误信息输出到 HttpResonse

以下提供定义全局异常的处理器。

@Component
public class DefaultRestApiErrorHandler implements RestApiErrorHandler {
@SneakyThrows
@Override
public void renderError(HttpServletRequest request, HttpServletResponse response, Throwable throwable) {
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
Response<Object> result = Response.failure(throwable.getMessage());
String json = Json.toJson(result);
StreamUtils.copy(json, StandardCharsets.UTF_8, response.getOutputStream());
}
}

RestApiUtils 工具类使用

RestApiUtils 主要是为了简化原生接口开发而使用,以下详细介绍相关使用方法。

  • path value 相关的
// 将 path value 转成 map
public static Map<String, String> extractPathValue(HttpServletRequest req);
// 将 path value 转为 Object
public static <T> T extractPathValue(HttpServletRequest req, Class<T> clzz);
// 将 path value 转为简单类型
public static <T> T extractPathValue(HttpServletRequest req, String name, Class<T> clzz);
  • form参数相关
// 将请求参数转为map
public static Map<String, Object> extractParam(HttpServletRequest req);
// 将请求参数转为对象
public static <T> T extractParam(HttpServletRequest req, Class<T> clzz);
  • json参数相关
// 解析json请求为map
public static Map<String, Object> extractBody(HttpServletRequest req);
// 解析json请求为对象
public static <T> T extractBody(HttpServletRequest req, Class<T> clzz);
  • json响应相关
// 输出json响应
public static void toJsonResp(HttpServletResponse resp, Object obj);