请求接收阶段说明.md
3.36 KB
请求接收阶段说明
阶段概述
请求接收阶段是网关调度的第一个环节,负责接收所有HTTP请求并进行初步处理。AppController作为统一网关入口,通过@RequestMapping注解定义路由规则,接收来自客户端的各种HTTP请求。
核心组件
- AppController: 网关入口控制器
- HttpServletRequest: HTTP请求对象
- @PathVariable/@RequestBody: Spring MVC参数绑定注解
处理流程
1. 请求路由
- 客户端发送请求到
/app/{service}路径 - AppController根据HTTP方法路由到对应方法:
servicePost: 处理POST请求serviceGet: 处理GET请求
2. 参数绑定
// POST请求参数绑定
@RequestMapping(path = "/{service:.+}", method = RequestMethod.POST)
public ResponseEntity<String> servicePost(@PathVariable String service,
@RequestBody String postInfo,
HttpServletRequest request)
// GET请求参数绑定
@RequestMapping(path = "/{service:.+}", method = RequestMethod.GET)
public ResponseEntity<String> serviceGet(@PathVariable String service,
HttpServletRequest request)
3. 头信息初始化
调用 getRequestInfo() 方法:
- 从HttpServletRequest中提取用户信息
- 获取认证token
- 封装标准化的请求头信息到Map中
代码示例
请求头信息封装方法
private void getRequestInfo(HttpServletRequest request, Map<String, String> headers) {
// 从请求中提取用户信息、token等
// 封装到headers Map中
headers.put(CommonConstant.HTTP_USER_ID, getUserId(request));
headers.put(CommonConstant.HTTP_APP_ID, getAppId(request));
// ... 其他头信息
}
典型POST请求处理
@RequestMapping(path = "/{service:.+}", method = RequestMethod.POST)
public ResponseEntity<String> servicePost(@PathVariable String service,
@RequestBody String postInfo,
HttpServletRequest request) {
// 初始化头信息
Map<String, String> headers = new HashMap<>();
this.getRequestInfo(request, headers);
// 设置服务编码和请求方法
headers.put(CommonConstant.HTTP_SERVICE, service);
headers.put(CommonConstant.HTTP_METHOD, CommonConstant.HTTP_METHOD_POST);
// 进入下一阶段:权限验证
// ...
}
关键配置
路由配置
@RequestMapping(path = "/{service:.+}", method = RequestMethod.POST)
@RequestMapping(path = "/{service:.+}", method = RequestMethod.GET)
请求头常量
public final static String HTTP_SERVICE = "SERVICE"; // 服务编码
public final static String HTTP_METHOD = "METHOD"; // 请求方法
public final static String HTTP_USER_ID = "USER_ID"; // 用户ID
public final static String HTTP_APP_ID = "APP_ID"; // 应用ID
输入输出
- 输入: HTTP请求(路径参数、请求体、头信息)
- 输出: 标准化的请求头信息Map,包含服务编码、用户信息等
异常处理
- 参数绑定异常
- 请求格式异常
- 服务编码解析异常
技术要点
- 使用正则表达式
/{service:.+}匹配所有服务路径 - 支持RESTful风格的HTTP方法
- 统一的请求头信息封装机制
- 与服务编码机制的紧密集成