Commit 5600389e authored by zhangc's avatar zhangc

添加api请求过滤规则,添加版本控制工具类,添加http请求工具类

parent 7bf63f95
......@@ -44,4 +44,8 @@ public class LoggingConstants {
/** "@" 符号*/
public static final String MONKEYS_AT = "@";
/** "&" 符号*/
public static final String AND_SPILT = "&";
}
......@@ -27,7 +27,8 @@ public enum GatewayResultCode implements ResultCode {
/** 无效参数 */
ILLEGAL_ARGUMENT("ILLEGAL_ARGUMENT", "无效参数"),
/** 参数列表为空 */
REQUEST_PARAM_EMPTY("REQUEST_PARAM_EMPTY", "请求参数为空"),
/** 无效请求 */
ILLEGAL_REQUEST("ILLEGAL_REQUEST", "无效请求"),
......@@ -35,8 +36,11 @@ public enum GatewayResultCode implements ResultCode {
/** 无效请求 */
ILLEGAL_TIMETEMP("ILLEGAL_TIMETEMP", "无效时间戳"),
/** 接口未授权 */
//INTERFACE_NO_AUTHORITY("INTERFACE_NO_AUTHORITY", "接口未授权"),
/** 请求次数受限 */
REQUEST_LIMIT_EXCEPTION("REQUEST_LIMIT_EXCEPTION", "请求次数受限"),
/** 请求超过限制 */
RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"),
......@@ -47,9 +51,22 @@ public enum GatewayResultCode implements ResultCode {
/** ip不允许访问 */
IP_NOT_ALLOW_ACCESS("IP_NOT_ALLOW_ACCESS", "ip不允许访问"),
/** 提交数据过大 */
POST_DATA_TOO_LARGE("POST_DATA_TOO_LARGE", "提交数据过大");
POST_DATA_TOO_LARGE("POST_DATA_TOO_LARGE", "提交数据过大"),
/** 签名错误 */
SIGN_ERROR("SIGN_EMPTY", "签名错误"),
/** 请求未授权 */
REQUEST_NOT_AUTH("REQUEST_NOT_AUTH", "请求未授权"),
/** 请求组织不存在 */
ORG_NOT_EXIST("ORG_NOT_EXIST", "请求组织不存在"),
/** API状态异常 */
API_STATUS_EXCEPTION("API_STATUS_EXCEPTION", "API状态异常"),
/** 请求组织状态异常 */
ORG_STATE_EXCEPTION("ORG_STATE_EXCEPTION", "请求组织状态异常");
/**
* 初始化保存到map里方便根据code获取
......
package com.jz.dm.common.exception;
import com.jz.dm.common.util.ResultCode;
/**
* 签名异常
*
*/
public class SignatureException extends OpenApiException {
private static final long serialVersionUID = 6551962245794846748L;
/**
* 构造函数
*
* @param resultCode
*/
public SignatureException(ResultCode resultCode) {
super(resultCode);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
*/
public SignatureException(ResultCode resultCode, String detailMessage) {
super(resultCode, detailMessage);
}
/**
* 构造函数
* @param resultCode
* @param cause
*/
public SignatureException(ResultCode resultCode, Throwable cause) {
super(resultCode, cause);
}
/**
* 构造函数
* @param resultCode
* @param detailMessage
* @param cause
*/
public SignatureException(ResultCode resultCode, String detailMessage, Throwable cause) {
super(resultCode, detailMessage, cause);
}
}
package com.jz.dm.common.util;
import java.util.Calendar;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.common.util
* @PROJECT_NAME: jz-dm-parent
* @NAME: DateUtil
* @DATE: 2021-1-2/21:55
* @DAY_NAME_SHORT: 周六
* @Description: 时间工具类处理时间
**/
public class DateUtil {
/**
* 计算当前距离23:59:59剩余时间
* @return
*/
public static long calculateNowResidueTime(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
}
public static void main(String[] args) {
System.out.println(calculateNowResidueTime());
}
}
package com.jz.dm.common.util;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.common.util
* @PROJECT_NAME: jz-dm-parent
* @NAME: MapUtil
* @DATE: 2021-1-2/14:02
* @DAY_NAME_SHORT: 周六
* @Description:
**/
public class MapUtil {
/**
* 对参数进行字典排序
* @param map
* @return
*/
public static List directSort(Map map){
List list = new ArrayList();
Iterator iter = map.entrySet().iterator(); //获得map的Iterator
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
list.add(entry.getKey());
}
Collections.sort(list);
return list;
}
/**
* 将对象转成TreeMap,属性名为key,属性值为value
* @param object 对象
* @return
* @throws IllegalAccessException
*/
public static TreeMap<String, Object> objToMap(Object object) throws IllegalAccessException {
Class clazz = object.getClass();
TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
while ( null != clazz.getSuperclass() ) {
Field[] declaredFields1 = clazz.getDeclaredFields();
for (Field field : declaredFields1) {
String name = field.getName();
// 获取原来的访问控制权限
boolean accessFlag = field.isAccessible();
// 修改访问控制权限
field.setAccessible(true);
Object value = field.get(object);
// 恢复访问控制权限
field.setAccessible(accessFlag);
if (null != value && StringUtils.isNotBlank(value.toString())) {
//如果是List,将List转换为json字符串
if (value instanceof List) {
value = JSON.toJSONString(value);
}
treeMap.put(name, value);
}
}
clazz = clazz.getSuperclass();
}
return treeMap;
}
/**
* 按照指定的分割符将list转换为String
* @param list
* @param separator
* @return
*/
public static String listToString(List list, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
if (i == list.size() - 1) {
sb.append(list.get(i));
} else {
sb.append(list.get(i));
sb.append(separator);
}
}
return sb.toString();
}
}
package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject;
import com.jz.common.utils.RedisUtils;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.constant.LoggingConstants;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.org.OrgStatusEnum;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.DateUtil;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.models.domian.ApiOrg;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.service.AuthService;
import com.jz.dm.service.OrganizationManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.filter
......@@ -15,8 +36,20 @@ import org.springframework.stereotype.Component;
* @Description: 认证过滤器
**/
@Component("authFilter")
@Slf4j
public class AuthFilter extends AbstractFilter {
@Autowired
private AuthService authService;
@Autowired
private OrganizationManageService organizationManageService;
@Autowired
private ApiInterfaceService apiInterfaceService;
@Autowired
private RedisUtils redisUtils;
@Value("${request.limit.max}")
private Long limit;
@Override
public String getFilterName() {
......@@ -27,10 +60,89 @@ public class AuthFilter extends AbstractFilter {
public int getOrder() {
return Constants.FILTER_ORDER_5;
}
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response, FilterChain chain) {
//TODO 主要做计费计次验证
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
try {
ApiInterface apiInterface = apiInterfaceService.getApiInfo(request.getAppKey());
if (null == apiInterface) {
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
if (!ApiStatusEnum.ISSUE.name().equals(apiInterface.getStatus())) {
throw new GatewayException(GatewayResultCode.API_STATUS_EXCEPTION);
}
JSONObject parameter = JSONObject.parseObject(request.getParams());
if (null != parameter) {
String authCode = parameter.getString("authCode");
ApiAuth authAuth = authService.getAuthUser(authCode);
if (null == authAuth) {
throw new GatewayException(GatewayResultCode.REQUEST_NOT_AUTH);
}
//查询认证组织信息
ApiOrg apiOrg = organizationManageService.getAuthOrganization(authAuth.getApiOrgId());
if (null == apiOrg) {
throw new GatewayException(GatewayResultCode.ORG_NOT_EXIST);
}
checkBill(request, authCode, authAuth, apiOrg);
}
} catch (Exception e) {
log.error("~~~~~~~~~~~~~~~~认证过滤异常~~~~~~~~~~~~~~~~~");
log.error("异常信息:{}", e.getMessage());
}
chain.doFilter(request, response);
}
/**
* 校验计费信息
* @param request
* @param authCode
* @param authAuth
* @param apiOrg
* @throws ParseException
*/
private void checkBill(GatewayRequest request, String authCode,
ApiAuth authAuth, ApiOrg apiOrg) throws ParseException {
switch (authAuth.getAuthMode()) {
case "POWER_CALL_MODE": //按次调用
//状态检查(只限制按次请求$$ 不限制按时间请求)
if (!OrgStatusEnum.NORMAL.name().equals(apiOrg.getStatus())) {
throw new GatewayException(GatewayResultCode.ORG_STATE_EXCEPTION);
}
//查询数据银行银行余额是否充足
try { //记录请求次数(每天限制请求次数)
String limitKey = request.getAppKey() + LoggingConstants.AND_SPILT + authCode;
String reqKey = redisUtils.get(limitKey);
long timeOut = DateUtil.calculateNowResidueTime();
if (null != reqKey) {
Integer value = Integer.valueOf(reqKey);
if (value > limit) {//超出最大请求次数
throw new GatewayException(GatewayResultCode.REQUEST_LIMIT_EXCEPTION);
} else if (value <= limit) {
redisUtils.delAndAdd(limitKey, limitKey, value + 1, timeOut);
}
} else {
redisUtils.set(limitKey, 1, timeOut);
}
} catch (Exception ex) {
log.error("~~~~~~~~~~~~~~~~~~~~~~过滤计次信息异常~~~~~~~~~~~~~~~~~~~");
log.error("异常信息:{}", ex.getMessage());
}
break;
case "RECORD_TIME_MODE": //按时间调用
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
String formatDate = dateFormat.format(new Date());
Date currentDate = dateFormat.parse(formatDate);
Date validEndTime = authAuth.getValidEndTime();
//如果 date1 在 date2 之前,before 返回 true,否则返回 false
if (currentDate.before(validEndTime)) {//超出时间
throw new GatewayException(GatewayResultCode.RATE_LIMIT_EXCEEDED);
}
break;
case "PERMANENT_TIME_MODE"://永久有效(直接跳出)
break;
default:
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
}
}
package com.jz.dm.filter;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.enums.Format;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.SignType;
import com.jz.dm.common.util.StringUtil;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
import com.jz.dm.common.enums.Format;
import com.jz.dm.common.enums.GatewayResultCode;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
/**
* 参数检查过滤器
*
......@@ -22,7 +20,7 @@ public class CheckArgsFilter extends AbstractFilter {
@Override
public int getOrder() {
return Constants.FILTER_ORDER_3;
return Constants.FILTER_ORDER_2;
}
@Override
......@@ -34,23 +32,20 @@ public class CheckArgsFilter extends AbstractFilter {
FilterChain chain) {
// 校验参数非空
if (StringUtil.isEmpty(request.getAppKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getCharset()) || StringUtil.isEmpty(request.getSignType())
|| StringUtil.isEmpty(request.getSign()) || StringUtil.isEmpty(request.getTimestamp())
|| StringUtil.isEmpty(request.getVersion())
|| StringUtil.isEmpty(request.getParams())) {
//无效参数
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
|| StringUtil.isEmpty(request.getSignType())|| StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getTimestamp())|| StringUtil.isEmpty(request.getParams())) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
}
// 设置默认值
if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name());
}
try {
request.setVersion("v1.0.0");
//格式,目前仅支持JSON
Format.valueOf(request.getFormat());
//请求使用的编码格式,如UTF-8,GBK,GB2312等
Charset.forName(request.getCharset());
//Charset.forName(request.getCharset());
//生成签名字符串所使用的签名算法类型
SignType.valueOf(request.getSignType());
} catch (Exception ex) {
......
......@@ -2,14 +2,13 @@ package com.jz.dm.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.LogUtil;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.constant.LoggingConstants;
import com.jz.dm.common.util.LogUtil;
import com.jz.dm.gateway.DefaultOpenApiDispatcher;
import com.jz.dm.models.enity.*;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.enums.RouteType;
import com.jz.dm.models.enity.DispatchContext;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
......@@ -45,19 +44,17 @@ public class InvokeRouteFilter extends AbstractFilter {
//当前系统时间戳
long startTime = System.currentTimeMillis();
try {
OpenApi openApi = (OpenApi) RequestContext.getCurrentContext().get("openApi");
if (openApi.getRouteType() == null) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ROUTE_TYPE);
}
if (openApi.getRouteType() != RouteType.SRPING) {
chain.doFilter(request, response);
return;
}
//OpenApi openApi = (OpenApi) RequestContext.getCurrentContext().get("openApi");
//if (openApi.getRouteType() == null) {
// throw new GatewayException(GatewayResultCode.ILLEGAL_ROUTE_TYPE);
//}
//if (openApi.getRouteType() != RouteType.SRPING) {
// chain.doFilter(request, response);
// return;
//}
DispatchContext context = new DispatchContext();
context.setAppKey(request.getAppKey());//apiKey
context.setApplication(openApi.getApplication());//应用
//context.setApplication(openApi.getApplication());//应用
context.setOpenApiMethod(request.getMethod()); //方法 例如:tradd.add
context.setOpenApiParams(request.getParams());//入参
context.setOpenApiVersion(request.getVersion()); //版本号
......
package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.common.constant.Constants;
import com.jz.dm.common.constant.LoggingConstants;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.exception.GatewayException;
import com.jz.dm.common.util.MapUtil;
import com.jz.dm.common.util.Md5;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse;
import com.jz.dm.models.enity.OpenApi;
import com.jz.dm.models.enity.RequestContext;
import com.jz.dm.common.enums.RouteType;
import com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.TreeMap;
/**
* 验签过滤器(验证签名信息)
*/
......@@ -16,9 +26,11 @@ import org.springframework.stereotype.Component;
@Component
public class VerifySignFilter extends AbstractFilter {
@Autowired
private ApiInterfaceService apiInterfaceService;
@Override
public int getOrder() {
return Constants.FILTER_ORDER_2;
return Constants.FILTER_ORDER_3;
}
@Override
......@@ -28,11 +40,35 @@ public class VerifySignFilter extends AbstractFilter {
@Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) {
try {
TreeMap<String, Object> map = MapUtil.objToMap(request);
if (null == map){
log.info("~~~~~~~~~~~~~~~签名数据转换map异常~~~~~~~~~~~~~~~~~~");
throw new GatewayException(GatewayResultCode.UNKNOWN_EXCEPTION);
}
List signParams = MapUtil.directSort(map);
if (CollectionUtils.isNotEmpty(signParams)){
JSONObject jsonObject = JSONObject.parseObject(request.getParams());
//需要传入授权码
ApiAuth apiAuthInfo = apiInterfaceService.getApiAuthInfo(request.getAppKey(), jsonObject.getString("authCode"));
if (null == apiAuthInfo){
throw new GatewayException(GatewayResultCode.ILLEGAL_REQUEST);
}
String paramStr = MapUtil.listToString(signParams, LoggingConstants.AND_SPILT);
String salt = Md5.encrypt(paramStr, apiAuthInfo.getSalt());
if (!request.getSign().equals(salt)){
throw new GatewayException(GatewayResultCode.SIGN_ERROR);
}
}
} catch(Exception e) {
log.error("~~~~~~~~~~~~~~签名过滤异常~~~~~~~~~~~~~~~~~~");
log.error("异常信息:{}",e.getMessage());
}
// 后期再扩展
OpenApi openApi = new OpenApi();
openApi.setApplication("JZ_API_GATEWAY");//应用
openApi.setRouteType(RouteType.SRPING);//漏油类型
RequestContext.getCurrentContext().set("openApi", openApi);
//OpenApi openApi = new OpenApi();
//openApi.setApplication("JZ_API_GATEWAY");//应用
//openApi.setRouteType(RouteType.SRPING);//漏油类型
//RequestContext.getCurrentContext().set("openApi", openApi);
chain.doFilter(request, response);
}
......
package com.jz.dm.models.enity;
import lombok.Data;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
......@@ -7,6 +9,7 @@ import java.util.Map;
/**
* Dispatch Context
*/
@Data
public class DispatchContext implements Serializable {
/**
......@@ -15,15 +18,10 @@ public class DispatchContext implements Serializable {
private static final long serialVersionUID = -3448256355423553719L;
/**
* 商户应用id
* api唯一标识
*/
private String appKey;
/**
* 应用
*/
private String application;
/**
* openapi接口
*/
......@@ -44,95 +42,6 @@ public class DispatchContext implements Serializable {
*/
private final Map<String, Object> extAttributes = new HashMap<String, Object>();
/**
* Getter method for property <tt>appId</tt>.
*
* @return property value of appId
*/
public String getAppKey() {
return appKey;
}
/**
* Setter method for property <tt>appId</tt>.
*
* @param appKey value to be assigned to property appId
*/
public void setAppKey(String appKey) {
this.appKey = appKey;
}
/**
* Getter method for property <tt>application</tt>.
*
* @return property value of application
*/
public String getApplication() {
return application;
}
/**
* Setter method for property <tt>application</tt>.
*
* @param application value to be assigned to property application
*/
public void setApplication(String application) {
this.application = application;
}
/**
* Getter method for property <tt>openApiMethod</tt>.
*
* @return property value of openApiMethod
*/
public String getOpenApiMethod() {
return openApiMethod;
}
/**
* Setter method for property <tt>openApiMethod</tt>.
*
* @param openApiMethod value to be assigned to property openApiMethod
*/
public void setOpenApiMethod(String openApiMethod) {
this.openApiMethod = openApiMethod;
}
/**
* Getter method for property <tt>openApiParams</tt>.
*
* @return property value of openApiParams
*/
public String getOpenApiParams() {
return openApiParams;
}
/**
* Setter method for property <tt>openApiParams</tt>.
*
* @param openApiParams value to be assigned to property openApiParams
*/
public void setOpenApiParams(String openApiParams) {
this.openApiParams = openApiParams;
}
/**
* Getter method for property <tt>openApiVersion</tt>.
*
* @return property value of openApiVersion
*/
public String getOpenApiVersion() {
return openApiVersion;
}
/**
* Setter method for property <tt>openApiVersion</tt>.
*
* @param openApiVersion value to be assigned to property openApiVersion
*/
public void setOpenApiVersion(String openApiVersion) {
this.openApiVersion = openApiVersion;
}
/**
* 获取扩展属性
......@@ -169,7 +78,7 @@ public class DispatchContext implements Serializable {
*/
@Override
public String toString() {
return "DispatchContext [application=" + application + ", openApiMethod=" + openApiMethod
return "DispatchContext [openApiMethod=" + openApiMethod
+ ", openApiParams=" + openApiParams + ", openApiVersion=" + openApiVersion + "]";
}
......
......@@ -2,6 +2,9 @@ package com.jz.dm.models.enity;
import com.jz.dm.web.annotation.ParamName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.HashMap;
......@@ -9,261 +12,46 @@ import java.util.Map;
/**
* api请求
*
* @author ZC
* @author zc
*/
@ApiModel("api请求实体类")
@Data
public class GatewayRequest implements Serializable {
/**
* 分配的ID
*/
@ParamName("app_key")
@ApiModelProperty(value = "appKey API唯一标识")
private String appKey;
/**
* 接口名称
*/
@ApiModelProperty(value = "接口名称")
private String method;
/**
* 格式,目前仅支持JSON
*/
@ApiModelProperty(value = "格式,目前仅支持JSON")
private String format;
/**
* 请求使用的编码格式,如UTF-8,GBK,GB2312等
*/
private String charset;
//private String charset;
/**
* 生成签名字符串所使用的签名算法类型
*/
@ParamName("sign_type")
@ApiModelProperty(value = "生成签名字符串所使用的签名算法类型")
private String signType;
/**
* 请求参数的签名串
*/
@ApiModelProperty(value = "请求参数的签名串")
private String sign;
/**
* 发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"
*/
@ApiModelProperty(value = "发送请求的时间,格式yyyy-MM-dd HH:mm:ss")
private String timestamp;
/**
* 调用的接口版本,固定为:1.0
*/
@ApiModelProperty(value="调用的接口版本,固定为:1.0")
private String version;
/**
* 请求参数,JSON格式
*/
@ApiModelProperty(value="请求参数,JSON格式")
private String params;
/**
* 扩展属性
*/
@ApiModelProperty(value="扩展属性")
private final Map<String, Attribute> extAttributes = new HashMap<String, Attribute>();
/**
* Getter method for property <tt>appId</tt>.
*
* @return property value of appId
*/
public String getAppKey() {
return appKey;
}
/**
* Setter method for property <tt>appId</tt>.
*
* @param appKey value to be assigned to property appId
*/
public void setAppKey(String appKey) {
this.appKey = appKey;
}
/**
* Getter method for property <tt>method</tt>.
*
* @return property value of method
*/
public String getMethod() {
return method;
}
/**
* Setter method for property <tt>method</tt>.
*
* @param method value to be assigned to property method
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Getter method for property <tt>format</tt>.
*
* @return property value of format
*/
public String getFormat() {
return format;
}
/**
* Setter method for property <tt>format</tt>.
*
* @param format value to be assigned to property format
*/
public void setFormat(String format) {
this.format = format;
}
/**
* Getter method for property <tt>charset</tt>.
*
* @return property value of charset
*/
public String getCharset() {
return charset;
}
/**
* Setter method for property <tt>charset</tt>.
*
* @param charset value to be assigned to property charset
*/
public void setCharset(String charset) {
this.charset = charset;
}
/**
* Getter method for property <tt>signType</tt>.
*
* @return property value of signType
*/
public String getSignType() {
return signType;
}
/**
* Setter method for property <tt>signType</tt>.
*
* @param signType value to be assigned to property signType
*/
public void setSignType(String signType) {
this.signType = signType;
}
/**
* Getter method for property <tt>sign</tt>.
*
* @return property value of sign
*/
public String getSign() {
return sign;
}
/**
* Setter method for property <tt>sign</tt>.
*
* @param sign value to be assigned to property sign
*/
public void setSign(String sign) {
this.sign = sign;
}
/**
* Getter method for property <tt>timestamp</tt>.
*
* @return property value of timestamp
*/
public String getTimestamp() {
return timestamp;
}
/**
* Setter method for property <tt>timestamp</tt>.
*
* @param timestamp value to be assigned to property timestamp
*/
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
/**
* Getter method for property <tt>version</tt>.
*
* @return property value of version
*/
public String getVersion() {
return version;
}
/**
* Setter method for property <tt>version</tt>.
*
* @param version value to be assigned to property version
*/
public void setVersion(String version) {
this.version = version;
}
/**
* Getter method for property <tt>notifyUrl</tt>.
*
* @return property value of notifyUrl
*/
// public String getNotifyUrl() {
// return notifyUrl;
//}
/**
* Setter method for property <tt>notifyUrl</tt>.
*
* @param notifyUrl value to be assigned to property notifyUrl
*/
//public void setNotifyUrl(String notifyUrl) {
// this.notifyUrl = notifyUrl;
//}
/**
* Getter method for property <tt>returnUrl</tt>.
*
* @return property value of returnUrl
*/
//public String getReturnUrl() {
// return returnUrl;
//}
/**
* Setter method for property <tt>returnUrl</tt>.
*
* @param returnUrl value to be assigned to property returnUrl
*/
// public void setReturnUrl(String returnUrl) {
// this.returnUrl = returnUrl;
// }
/**
* Getter method for property <tt>params</tt>.
*
* @return property value of params
*/
public String getParams() {
return params;
}
/**
* Setter method for property <tt>params</tt>.
*
* @param params value to be assigned to property params
*/
public void setParams(String params) {
this.params = params;
}
/**
* 获取扩展属性
*
......@@ -301,7 +89,7 @@ public class GatewayRequest implements Serializable {
@Override
public String toString() {
return "GatewayRequest [appKey=" + appKey + ", method=" + method + ", format=" + format
+ ", charset=" + charset + ", signType=" + signType + ", sign=" + sign
+ ", signType=" + signType + ", sign=" + sign
+ ", timestamp=" + timestamp + ", version=" + version
+ ", params=" + params + ", extAttributes="
+ extAttributes + "]";
......
package com.jz.dm.service;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiInterfaceService
* @DATE: 2021-1-2/14:26
* @DAY_NAME_SHORT: 周六
* @Description:
**/
public interface ApiInterfaceService {
/**
* 根据Api授权码获取用户授权信息
* @param apiKey
* @param authCode
* @return
*/
ApiAuth getApiAuthInfo(String apiKey,String authCode);
/**
* 获取api信息
* @param appKey
* @return
*/
ApiInterface getApiInfo(String appKey);
}
package com.jz.dm.service;
import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.req.auth.*;
/**
......@@ -54,4 +55,11 @@ public interface AuthService {
* @return
*/
Result updateSaltInfo(SaltResetReq req);
/**
* 获取API授权信息
* @param authCode
* @return
*/
ApiAuth getAuthUser( String authCode);
}
......@@ -52,4 +52,11 @@ public interface OrganizationManageService {
* @return
*/
Result delete(Long id);
/**
* 获取认证组织信息
* @param apiOrgId
* @return
*/
ApiOrg getAuthOrganization(Long apiOrgId);
}
package com.jz.dm.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jz.dm.mapper.ApiAuthMapper;
import com.jz.dm.mapper.ApiInterfaceMapper;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.domian.ApiInterface;
import com.jz.dm.service.ApiInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service.impl
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiInterfaceServiceImpl
* @DATE: 2021-1-2/14:27
* @DAY_NAME_SHORT: 周六
* @Description:
**/
@Service("apiInterfaceService")
@Slf4j
public class ApiInterfaceServiceImpl implements ApiInterfaceService {
@Resource
private ApiInterfaceMapper apiInterfaceMapper;
@Resource
private ApiAuthMapper apiAuthMapper;
/**
* 获取用户授权信息
* @param apiKey
* @param authCode
* @return
*/
@Override
public ApiAuth getApiAuthInfo(String apiKey, String authCode) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("is_deleted",0);
query.eq("api_key", apiKey);
ApiInterface apiInterface = apiInterfaceMapper.selectOne(query);
if (null != apiInterface){
QueryWrapper<ApiAuth> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("is_deleted",0);
queryWrapper.eq("auth_code",authCode);
ApiAuth apiAuth = apiAuthMapper.selectOne(queryWrapper);
if (null != apiAuth){
return apiAuth;
}
}
return null;
}
/**
* 获取API信息
* @param appKey
* @return
*/
@Override
public ApiInterface getApiInfo(String appKey) {
QueryWrapper<ApiInterface> query = new QueryWrapper<>();
query.eq("is_deleted",0);
query.eq("api_key",appKey);
return apiInterfaceMapper.selectOne(query);
}
}
......@@ -264,6 +264,19 @@ public class AuthServiceImpl implements AuthService {
return Result.of_success(ResultMsg.UPDATE_FAIL);
}
/**
* 获取API授权信息
* @param authCode
* @return
*/
@Override
public ApiAuth getAuthUser(String authCode) {
QueryWrapper<ApiAuth> query = new QueryWrapper<>();
query.eq("auth_code",authCode);
query.eq("is_deleted",0);
return apiAuthMapper.selectOne(query);
}
private ApiInterface getInterface(String apiKey) {
QueryWrapper<ApiInterface> queryInface = new QueryWrapper<>();
queryInface.last("where is_deleted=0 and api_key ='" + apiKey + "'");
......
......@@ -184,6 +184,19 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_success(ResultMsg.DELETE_FAIL);
}
/**
* 获取认证组织信息
* @param apiOrgId
* @return
*/
@Override
public ApiOrg getAuthOrganization(Long apiOrgId) {
QueryWrapper<ApiOrg> query = new QueryWrapper<>();
query.eq("id",apiOrgId);
query.eq("is_deleted",0);
return apiOrgMapper.selectOne(query);
}
/**
* 根据名称获取组织信息
*
......
......@@ -9,6 +9,7 @@ import com.jz.common.bean.SysUserDto;
import com.jz.common.constant.RedisMessageConstant;
import com.jz.common.constant.ResultMsg;
import com.jz.common.exception.ResponseException;
import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.RedisUtils;
import com.jz.common.utils.Result;
import com.jz.dm.common.constant.TagConstants;
......@@ -16,7 +17,6 @@ import com.jz.dm.common.enums.GeneralStatusTypeEnum;
import com.jz.dm.common.enums.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.produce.ProducerStatusTypeEnum;
import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.common.util.WebUtils;
import com.jz.dm.mapper.*;
import com.jz.dm.models.domian.*;
import com.jz.dm.models.req.make.*;
......@@ -66,6 +66,8 @@ public class ProducerServiceImpl implements ProducerService {
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private RedisUtils redisUtils;
@Autowired
private HttpsUtils httpsUtils;
@Value("${dmp.openapi.timeout.max}")
private int maxTimeout;
......@@ -413,7 +415,7 @@ public class ProducerServiceImpl implements ProducerService {
}
JSONArray result = new JSONArray();
log.info("查询es标签类下的索引地址信息:" + datasource.getJdbcUrl() + "/es/get/indicess");
String resp = WebUtils.doGet(datasource.getJdbcUrl() + "/es/get/indicess", null);
String resp = httpsUtils.doGet(datasource.getJdbcUrl() + "/es/get/indicess", null);
if (resp != null) {
log.info("返回索引信息集合:" + resp);
JSONArray json = JSONArray.parseArray(resp);
......@@ -450,7 +452,7 @@ public class ProducerServiceImpl implements ProducerService {
JSONObject param = new JSONObject();
param.put("indices", indices);
log.info("参数集合:" + param.toString());
String resp = WebUtils.post(datasource.getJdbcUrl() + "/es/get/indices/types", param.toString());
String resp = httpsUtils.submitPost(datasource.getJdbcUrl() + "/es/get/indices/types", param.toString());
log.info("索引下type的信息集合:" + resp);
return Result.of_success(resp);
}
......@@ -473,12 +475,12 @@ public class ProducerServiceImpl implements ProducerService {
HashMap<String, String> herders = new HashMap<>();
herders.put("Content-Encoding", "UTF-8");
herders.put("Content-Type", "application/json");
HashMap<String, String> dataMap = new HashMap<>();
dataMap.put("indices", indices);
dataMap.put("type", type);
JSONObject param = new JSONObject();
param.put("indices", indices);
param.put("type", type);
String resp = null;
try {
resp = WebUtils.post(datasource.getJdbcUrl() + "/es/get/type/fields", herders, dataMap);
resp = httpsUtils.submitPost(datasource.getJdbcUrl() + "/es/get/type/fields", param.toString(),herders);
log.info("索引下type的fields信息集合:" + resp);
} catch (Exception e) {
e.printStackTrace();
......
package com.jz.dm.service.apirequest;
package com.jz.dm.service.request;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.common.enums.GatewayResultCode;
import com.jz.dm.common.util.OpenApiRequest;
import com.jz.dm.common.util.OpenApiResponse;
import com.jz.dm.gateway.OpenApiService;
import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.web.annotation.AccessLimit;
import com.jz.dm.web.annotation.ApiLogAspect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.dm.service.apirequest
* @PACKAGE_NAME: com.jz.dm.service.request
* @PROJECT_NAME: jz-dm-parent
* @NAME: ApiQueryService
* @DATE: 2020-12-23/18:10
......@@ -29,14 +34,42 @@ public class ApiQueryService implements OpenApiService {
@Override
public String getOpenApiVersion() {
return "1.0.0";
return "v1.0.0";
}
@Autowired
private ApiInterfaceService apiInterfaceService;
@Override
@ApiLogAspect
@ApiLogAspect(description = "API请求日志")
@AccessLimit(limit = 10000,sec = 1)
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
public void doService(OpenApiRequest request, OpenApiResponse response) {
JSONObject parameter = JSONObject.parseObject(request.getOpenApiParams());
String apiType = parameter.getString("apiType");
if (StringUtils.isNotBlank(apiType)){
try {
switch (apiType){
case "QUERY_TAG": //标签查询
//String reqParam = parameter.getString("request_param");
//apiInterfaceService.getTagReqData();
break;
case "BIG_DATA_QUERY"://大数据查询
break;
case "CUSTOM_QUERY": //自定义查询(三方查询)
break;
case "DATA_BAG_QUERY": //数据包查询
break;
default :
response.setCode(GatewayResultCode.ILLEGAL_REQUEST.getCode());
response.setMsg(GatewayResultCode.ILLEGAL_REQUEST.getMsg());
break;
}
} catch(Exception e) {
log.error("~~~~~~~~~~~~~~~请求api信息异常~~~~~~~~~~~~~");
log.error("异常信息:{}",e.getMessage());
response.setCode(GatewayResultCode.ILLEGAL_REQUEST.getCode());
response.setMsg(GatewayResultCode.ILLEGAL_REQUEST.getMsg());
}
}
}
}
......@@ -83,3 +83,6 @@ dmp:
timeout:
default: 5000
max: 5000
request:
limit:
max: 10
package com.jz.dm.gateway.orther;
import com.jz.dm.common.util.WebUtils;
import com.jz.common.utils.WebUtils;
import com.jz.dm.gateway.SpringTestCase;
import com.jz.dm.service.ProducerService;
import org.junit.Test;
......
package com.jz.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.HttpConnectionFactory;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @Description:
* @PROJECT_NAME: fbpay-broker
* @NAME: HttpClientPool
* @author: zc
* @DATE: 2020/9/14/9:37
* @DAY_NAME_SHORT: 周一
* Date Author Version Description
* -----------------------------------------------------*
* 2020/9/14 ZC v1.0.0 创建
**/
@Slf4j
public class HttpClientPool {
private static PoolingHttpClientConnectionManager manager = null;
private static CloseableHttpClient httpClient = null;
public static synchronized CloseableHttpClient getHttpClient() {
if (httpClient == null) {
System.out.println("---------------------------------------------------------创建");
//注册访问协议相关的Socket工厂
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", SSLConnectionSocketFactory.getSystemSocketFactory())
.build();
//HttpConnection 工厂:配置写请求/解析响应处理器
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory
= new ManagedHttpClientConnectionFactory(
DefaultHttpRequestWriterFactory.INSTANCE,
DefaultHttpResponseParserFactory.INSTANCE);
//DNS 解析器
DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE;
//创建池化连接管理器
manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connectionFactory, dnsResolver);
//默认为Socket配置
SocketConfig defaultSocketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
manager.setDefaultSocketConfig(defaultSocketConfig);
//设置整个连接池的最大连接数
manager.setMaxTotal(300);
//每个路由的默认最大连接,每个路由实际最大连接数由DefaultMaxPerRoute控制,而MaxTotal是整个池子的最大数
//设置过小无法支持大并发(ConnectionPoolTimeoutException) Timeout waiting for connection from pool
//每个路由的最大连接数
manager.setDefaultMaxPerRoute(200);
//在从连接池获取连接时,连接不活跃多长时间后需要进行一次验证,默认为2s
manager.setValidateAfterInactivity(5 * 1000);
//默认请求配置
RequestConfig defaultRequestConfig = RequestConfig.custom()
//设置连接超时时间,2s
.setConnectTimeout(2 * 1000)
//设置等待数据超时时间,5s
.setSocketTimeout(5 * 1000)
//设置从连接池获取连接的等待超时时间
.setConnectionRequestTimeout(2000)
.build();
//创建HttpClient
httpClient = HttpClients.custom()
.setConnectionManager(manager)
//连接池不是共享模式
.setConnectionManagerShared(false)
//定期回收空闲连接
.evictIdleConnections(60, TimeUnit.SECONDS)
// 定期回收过期连接
.evictExpiredConnections()
//连接存活时间,如果不设置,则根据长连接信息决定
.setConnectionTimeToLive(60, TimeUnit.SECONDS)
//设置默认请求配置
.setDefaultRequestConfig(defaultRequestConfig)
//连接重用策略,即是否能keepAlive
.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)
//长连接配置,即获取长连接生产多长时间
.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
//设置重试次数,默认是3次,当前是禁用掉(根据需要开启)
.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
.build();
//JVM 停止或重启时,关闭连接池释放掉连接(跟数据库连接池类似)
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("error when close httpClient:{}", e);
}
}
});
}
return httpClient;
}
}
package com.jz.common.utils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.jz.common.utils.HttpClientPool.getHttpClient;
/**
* @author ZC
* @PACKAGE_NAME: com.jz.common.utils
* @PROJECT_NAME: jz-dm-parent
* @NAME: HttpsUtils
* @DATE: 2021-1-3/0:29
* @DAY_NAME_SHORT: 周日
* @Description:
**/
@Slf4j
@Component
public class HttpsUtils {
/**
* Post请求表单提交
*
* @param url 请求路径
* @param params 请求参数
* @param headers 请求头
* @return
*/
public String submitPost(String url, String params, Map<String, String> headers) {
CloseableHttpClient httpClient = getHttpClient();
String body = null;
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
if (null != headers && headers.size() > 0) {
for (Map.Entry<String, String> e : headers.entrySet()) {
httpPost.addHeader(e.getKey(), e.getValue());
}
}
if (StringUtils.isNotBlank(params)) {
httpPost.setEntity(new StringEntity(params, Consts.UTF_8));
}
response = httpClient.execute(httpPost);
body = getBody(response.getEntity());
log.info("请求:" + url + "---->返回结果:" + body);
} catch (IOException e) {
log.error("请求:" + url + "--->异常", e);
} finally {
try {// 释放链接
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return body;
}
/**
* Post请求表单提交
*
* @param url 请求路径
* @param params 请求参数
* @return
*/
public String submitPost(String url, String params) {
CloseableHttpClient httpClient = getHttpClient();
String body = null;
CloseableHttpResponse response = null;
try {
HttpPost httpPost = new HttpPost(url);
if (StringUtils.isNotBlank(params)) {
httpPost.setEntity(new StringEntity(params, Consts.UTF_8));
}
response = httpClient.execute(httpPost);
body = getBody(response.getEntity());
log.info("请求:" + url + "---->返回结果:" + body);
} catch (IOException e) {
log.error("请求:" + url + "--->异常", e);
} finally {
try {// 释放链接
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return body;
}
/**
* 验证码实时校验
* 无需cookie和referer时请求接口
*
* @param params 入参
* @param baseUrl 发送请求的URL
* @return URL 所代表远程资源的响应结果
*/
public String doGet(String baseUrl, Map<String, String> params) {
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
String body = null;
try {
List<String> mapList = new ArrayList<>();
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
mapList.add(entry.getKey() + "=" + entry.getValue());
}
}
if (CollectionUtils.isNotEmpty(mapList)) {
baseUrl = baseUrl + "?";
String paramsStr = StringUtils.join(mapList, "&");
baseUrl = baseUrl + paramsStr;
}
HttpGet httpGet = new HttpGet(baseUrl);
response = httpClient.execute(httpGet);
body = getBody(response.getEntity());
log.info("获取请求结果为:" + body);
} catch (Exception e) {
log.warn("请求接口时-->" + baseUrl + "发生异常:", e);
} finally {
try {
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return body;
}
/**
* 验证码实时校验
* 无需cookie和referer时请求接口
* @param baseUrl 发送请求的URL
* @param params 请求参数
* @return URL 所代表远程资源的响应结果
*/
public String doGet(String baseUrl,Map<String, String> params, Map<String, String> headers) {
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
String body = null;
try {
List<String> mapList = new ArrayList<>();
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
mapList.add(entry.getKey() + "=" + entry.getValue());
}
}
if (CollectionUtils.isNotEmpty(mapList)) {
baseUrl = baseUrl + "?";
String paramsStr = StringUtils.join(mapList, "&");
baseUrl = baseUrl + paramsStr;
}
HttpGet httpGet = new HttpGet(baseUrl);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> e : headers.entrySet()) {
httpGet.addHeader(e.getKey(), e.getValue());
}
}
response = httpClient.execute(httpGet);
body = getBody(response.getEntity());
log.info("获取请求结果为:" + body);
} catch (Exception e) {
log.warn("请求接口时-->" + baseUrl + "发生异常:", e);
} finally {
try {
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return body;
}
/**
* 获取图片二维码
*
* @param url
* @throws IOException
*/
public CloseableHttpClient doGetImg(String url) {
CloseableHttpClient httpClient = getHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
httpClient.execute(httpGet);
} catch (IOException e) {
log.error("发起http request异常:{}", e);
}
return httpClient;
}
/**
* 获取图片二维码
*
* @param url
* @throws IOException
*/
public HttpEntity doGetImg(String url, Map<String, String> headers) {
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> e : headers.entrySet()) {
httpGet.addHeader(e.getKey(), e.getValue());
}
}
try {
response = httpClient.execute(httpGet);
} catch (IOException e) {
log.error("发起http request异常:{}", e);
}
return response.getEntity();
}
public static String getBody(HttpEntity entity) throws ParseException, IOException {
String body = "";
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, Consts.UTF_8);
}
EntityUtils.consume(entity);
return body;
}
}
......@@ -3,6 +3,7 @@
*/
package com.jz.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
......@@ -20,6 +21,7 @@ import java.util.concurrent.TimeUnit;
* @version $Id: RedisUtils.java 2019年11月2日 上午8:36:41 $
*/
@Component("redisUtils")
@Slf4j
public class RedisUtils {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
......@@ -238,4 +240,21 @@ public class RedisUtils {
return redisTemplate.opsForList().range(key, 0, 500);
}
/**
* 删除久key值,添加新key值
* @param nowKey
* @param newKey
* @param value
* @param timeout
* @return
*/
public void delAndAdd(String nowKey,String newKey,Integer value,long timeout){
try {
redisTemplate.delete(nowKey);
redisTemplate.opsForValue().set(newKey,value,timeout);
}catch (Exception e) {
log.error("~~~~~~~~~~~~~保存redis计次异常~~~~~~~~~~~~~~~~~~~");
e.printStackTrace();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment