承接上文,params參數可以從數據庫中查詢
String params = "{\"user_id\":\"${userId}\",\"endTime\":\"${inTimeStamp}\",\"startTime\":\"${startTimeStamp}\",\"token\":\"user_agent_message\",\"limit\":\"10\",\"tags\":\"\"}";
在項目中的用法
JSONObject handler(ThirdReqVo thirdReqVo) {
JSONObject result = new JSONObject();
List<HttpConfiguration>
httpConfigs =
httpInterfaceConfig.loadHttpConfigs(thirdReqVo.getQuerySource());
for (HttpConfiguration configuration : httpConfigs) {
Map<String, Object> variables = buildVariables(thirdReqVo);
JSONObject jsonObject = cacheOrRequest(configuration, variables);
result.put(configuration.getHttpName(), jsonObject);
}
return result;
}
private Map<String, Object> buildVariables(ThirdReqVo thirdReqVo) {
Map<String, Object> variables = Maps.newHashMap();
variables.put("orderId", thirdReqVo.getBusinessId());
variables.put("order_id", thirdReqVo.getBusinessId());
variables.put("user_id", thirdReqVo.getUserId());
variables.put("userId", thirdReqVo.getUserId());
variables.put("channel", thirdReqVo.getPlatformNo());
variables.put("type", thirdReqVo.getType().getCode());
variables.put("query_source", thirdReqVo.getQuerySource());
variables.put("encryptUserId", thirdReqVo.getEncryptUserId());
return variables;
}
private JSONObject cacheOrRequest(HttpConfiguration configuration,
Map<String, Object> variables) {
String params = configuration.getParams();
String url = configuration.getHostUrl() + "/" + configuration.getPath();
url = url.replaceAll("///","/").replaceAll("//","/");
String parse = MapVariablesParser.parse(params, variables);
JSONObject paramsMap = JSON.parseObject(parse);
String mediaTypeStr = configuration.getMediaType();
MediaType mediaType;
String res = null;
if (StringUtils.isNotBlank(mediaTypeStr) && mediaTypeStr.contains("json")) {
mediaType = OkHttpUtil.MEDIA_JSON;
} else {
mediaType = OkHttpUtil.MEDIA_FORM;
}
String redisKey = url + parse;
try {
res = (String) baseRedis.getString(redisKey);
} catch (Exception e) {
log.error("獲取接口緩存異常", e);
}
try {
if (res == null) {
res = OkHttpUtil.post(url, paramsMap, mediaType);
baseRedis.setString(redisKey, res, 30);
return JSON.parseObject(res);
} else {
log.info("[獲取到緩存數據] url:[{}],params:[{}],result:[{}]", url,
JSON.toJSONString(paramsMap), res);
return JSON.parseObject(res);
}
} catch (Exception e) {
log.error("請求http接口異常", e);
return new JSONObject();
}
}