88e030b7
王彪总
init project
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
# 响应返回阶段说明
## 阶段概述
响应返回阶段是网关调度的最后一个环节,负责处理微服务返回结果、统一封装响应格式、记录事务日志和性能监控。确保客户端收到标准化、格式统一的响应数据。
## 核心组件
- **ResponseEntity**: Spring响应实体
- **ResultVo**: 统一响应结果封装类
- **事务日志组件**: 记录请求链路信息
- **性能监控组件**: 记录请求耗时和性能指标
## 处理流程
### 1. 响应结果处理
- 接收下游微服务返回的业务结果
- 处理业务异常和系统异常
- 统一封装响应格式
### 2. 响应格式封装
```java
// 统一响应格式封装
ResponseEntity<String> responseEntity = ResultVo.createResponseEntity(resultData, HttpStatus.OK);
```
### 3. 事务日志记录
- 记录完整的请求链路信息
- 保存请求和响应数据
- 记录处理耗时和性能指标
### 4. 响应头设置
- 设置Content-Type等响应头信息
- 处理跨域相关头信息
- 设置缓存控制头
## 代码示例
### 统一响应结果封装类
```java
public class ResultVo {
public static ResponseEntity<String> createResponseEntity(Object data, HttpStatus status) {
Map<String, Object> result = new HashMap<>();
result.put("code", status.value());
result.put("message", "success");
result.put("data", data);
result.put("timestamp", System.currentTimeMillis());
return new ResponseEntity<>(JSONObject.toJSONString(result), status);
}
public static ResponseEntity<String> error(String message, HttpStatus status) {
Map<String, Object> result = new HashMap<>();
result.put("code", status.value());
result.put("message", message);
result.put("data", null);
result.put("timestamp", System.currentTimeMillis());
return new ResponseEntity<>(JSONObject.toJSONString(result), status);
}
}
```
### 在网关中的完整响应处理
```java
@RequestMapping(path = "/{service:.+}", method = RequestMethod.POST)
public ResponseEntity<String> servicePost(@PathVariable String service,
@RequestBody String postInfo,
HttpServletRequest request) {
long startTime = System.currentTimeMillis();
ResponseEntity<String> responseEntity = null;
try {
// 1. 请求接收阶段
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);
// 2. 权限验证阶段
IPageData pd = (IPageData) request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA);
privilegeSMOImpl.hasPrivilege(restTemplate, pd, "/app/" + service);
// 3. 服务分发阶段
responseEntity = apiSMOImpl.doApi(postInfo, headers, request);
// 4. 响应返回阶段 - 记录成功日志
long endTime = System.currentTimeMillis();
logTransaction(request, service, postInfo, responseEntity, endTime - startTime, true);
} catch (Throwable e) {
logger.error("请求方法失败", e);
// 4. 响应返回阶段 - 记录异常日志
long endTime = System.currentTimeMillis();
responseEntity = ResultVo.error("请求发生异常," + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
logTransaction(request, service, postInfo, responseEntity, endTime - startTime, false);
}
return responseEntity;
}
```
### 事务日志记录方法
```java
private void logTransaction(HttpServletRequest request, String service,
String requestData, ResponseEntity<String> response,
long costTime, boolean success) {
TransactionLog log = new TransactionLog();
log.setServiceCode(service);
log.setRequestUrl(request.getRequestURI());
log.setRequestMethod(request.getMethod());
log.setRequestData(requestData);
log.setResponseData(response.getBody());
log.setStatusCode(response.getStatusCodeValue());
log.setCostTime(costTime);
log.setSuccess(success);
log.setCreateTime(new Date());
// 异步保存事务日志
transactionLogService.asyncSave(log);
}
```
## 关键配置
### 响应格式配置
```java
// 统一响应格式
{
"code": 200,
"message": "success",
"data": {...},
"timestamp": 1638254632000
}
```
### 响应头配置
```java
// 跨域响应头配置
responseEntity.getHeaders().set("Access-Control-Allow-Origin", "*");
responseEntity.getHeaders().set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
responseEntity.getHeaders().set("Access-Control-Allow-Headers", "Content-Type, Authorization");
```
## 响应处理机制
### 1. 统一格式封装
- 标准化响应数据结构
- 统一的错误码和消息格式
- 时间戳和请求追踪信息
### 2. 异常处理策略
- 业务异常:返回具体错误信息
- 系统异常:返回通用错误信息
- 权限异常:返回权限不足信息
### 3. 性能监控
- 记录请求处理总耗时
- 监控各阶段处理时间
- 性能指标统计和分析
### 4. 事务审计
- 完整的请求响应日志
- 操作记录和审计追踪
- 故障排查和问题定位
## 异常处理
### 响应封装异常
```java
try {
return ResultVo.createResponseEntity(resultData, HttpStatus.OK);
} catch (JsonProcessingException e) {
logger.error("响应数据序列化失败", e);
return ResultVo.error("响应数据格式异常", HttpStatus.INTERNAL_SERVER_ERROR);
}
```
### 日志记录异常
```java
try {
logTransaction(request, service, postInfo, responseEntity, costTime, true);
} catch (Exception e) {
// 日志记录异常不应影响主流程
logger.error("事务日志记录失败", e);
}
```
## 技术要点
1. **统一响应格式**: 标准化的API响应规范
2. **异步日志记录**: 不影响主流程的日志记录机制
3. **性能监控**: 完整的请求链路性能追踪
4. **错误处理**: 分层次的异常处理策略
## 性能优化
- 响应数据压缩
- 日志异步写入
- 连接及时释放
- 缓存合理使用
## 安全特性
- 敏感信息过滤
- 响应数据加密
- 防重放攻击
- 请求频率限制
|