|
|
|
# 自定义返回结果
|
|
|
|
|
|
|
|
网关默认对业务结果进行合并,然后返回统一的格式。
|
|
|
|
|
|
|
|
针对`alipay.story.find`接口,微服务端返回结果如下:
|
|
|
|
|
|
|
|
```json
|
|
|
|
{
|
|
|
|
"name": "白雪公主",
|
|
|
|
"id": 1,
|
|
|
|
"gmtCreate": 1554193987378
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
网关合并后,最终结果如下
|
|
|
|
|
|
|
|
```json
|
|
|
|
{
|
|
|
|
"alipay_story_find_response": {
|
|
|
|
"msg": "Success",
|
|
|
|
"code": "10000",
|
|
|
|
"name": "白雪公主",
|
|
|
|
"id": 1,
|
|
|
|
"gmtCreate": 1554193987378
|
|
|
|
},
|
|
|
|
"sign": "xxxxx"
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
其中`alipay_story_find_response`是它的数据节点。规则是:
|
|
|
|
|
|
|
|
> 将接口名中的点`.`转换成下划线`_`,后面加上`_response`
|
|
|
|
|
|
|
|
代码实现如下:
|
|
|
|
|
|
|
|
```java
|
|
|
|
String method = "alipay.story.find";
|
|
|
|
return method.replace('.', '_') + "_response";
|
|
|
|
```
|
|
|
|
|
|
|
|
详见`DefaultDataNameBuilder.java`
|
|
|
|
|
|
|
|
如果要更改数据节点,比如`result`,可使用`CustomDataNameBuilder.java`。
|
|
|
|
|
|
|
|
```java
|
|
|
|
@Configuration
|
|
|
|
public class ZuulConfig extends AlipayZuulConfiguration {
|
|
|
|
|
|
|
|
static {
|
|
|
|
...
|
|
|
|
ApiConfig.getInstance().setDataNameBuilder(new CustomDataNameBuilder());
|
|
|
|
...
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
设置后,网关统一的返回结果如下:
|
|
|
|
|
|
|
|
```json
|
|
|
|
{
|
|
|
|
"result": {
|
|
|
|
...
|
|
|
|
},
|
|
|
|
"sign": "xxxxx"
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
此外,构造方法可指定自定义字段名称:`new CustomDataNameBuilder("data");`。
|
|
|
|
设置后,数据节点将变成`data`
|
|
|
|
|
|
|
|
```json
|
|
|
|
{
|
|
|
|
"data": {
|
|
|
|
...
|
|
|
|
},
|
|
|
|
"sign": "xxxxx"
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
**注**:网关设置了CustomDataNameBuilder后,SDK也要做相应的更改:`OpenConfig.dataNameBuilder = new CustomDataNameBuilder();`
|
|
|
|
|
|
|
|
## 自定义结果处理
|
|
|
|
|
|
|
|
如果想要对微服务结果做更深一步处理,步骤如下:
|
|
|
|
|
|
|
|
1. 新增一个类,继承`ZuulResultExecutor.java`,并重写`public String merge(T exchange, JSONObject responseData)`方法
|
|
|
|
|
|
|
|
方法merge参数说明如下:
|
|
|
|
|
|
|
|
exchange:RequestContext对象
|
|
|
|
responseData:微服务端返回的结果
|
|
|
|
|
|
|
|
方法返回最终结果
|
|
|
|
|
|
|
|
2. 配置自定义类
|
|
|
|
|
|
|
|
```java
|
|
|
|
public class SopGatewayApplication {
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
ApiConfig.getInstance().setZuulResultExecutor(new MyzuulResultExecutor());
|
|
|
|
SpringApplication.run(SopGatewayApplication.class, args);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## 不合并结果
|
|
|
|
|
|
|
|
如果不希望对结果进行合并,可设置`ApiConfig.getInstance().setMergeResult(false);`
|
|
|
|
|
|
|
|
```java
|
|
|
|
public class SopGatewayApplication {
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
ApiConfig.getInstance().setMergeResult(false);
|
|
|
|
SpringApplication.run(SopGatewayApplication.class, args);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
这样,网关最终返回结果即为微服务端的返回结果。
|