Commit 5600389e authored by zhangc's avatar zhangc

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

parent 7bf63f95
...@@ -44,4 +44,8 @@ public class LoggingConstants { ...@@ -44,4 +44,8 @@ public class LoggingConstants {
/** "@" 符号*/ /** "@" 符号*/
public static final String MONKEYS_AT = "@"; public static final String MONKEYS_AT = "@";
/** "&" 符号*/
public static final String AND_SPILT = "&";
} }
...@@ -27,7 +27,8 @@ public enum GatewayResultCode implements ResultCode { ...@@ -27,7 +27,8 @@ public enum GatewayResultCode implements ResultCode {
/** 无效参数 */ /** 无效参数 */
ILLEGAL_ARGUMENT("ILLEGAL_ARGUMENT", "无效参数"), ILLEGAL_ARGUMENT("ILLEGAL_ARGUMENT", "无效参数"),
/** 参数列表为空 */
REQUEST_PARAM_EMPTY("REQUEST_PARAM_EMPTY", "请求参数为空"),
/** 无效请求 */ /** 无效请求 */
ILLEGAL_REQUEST("ILLEGAL_REQUEST", "无效请求"), ILLEGAL_REQUEST("ILLEGAL_REQUEST", "无效请求"),
...@@ -35,8 +36,11 @@ public enum GatewayResultCode implements ResultCode { ...@@ -35,8 +36,11 @@ public enum GatewayResultCode implements ResultCode {
/** 无效请求 */ /** 无效请求 */
ILLEGAL_TIMETEMP("ILLEGAL_TIMETEMP", "无效时间戳"), ILLEGAL_TIMETEMP("ILLEGAL_TIMETEMP", "无效时间戳"),
/** 接口未授权 */
//INTERFACE_NO_AUTHORITY("INTERFACE_NO_AUTHORITY", "接口未授权"),
/** 请求次数受限 */
REQUEST_LIMIT_EXCEPTION("REQUEST_LIMIT_EXCEPTION", "请求次数受限"),
/** 请求超过限制 */ /** 请求超过限制 */
RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"), RATE_LIMIT_EXCEEDED("RATE_LIMIT_EXCEEDED", "请求超过限制"),
...@@ -47,9 +51,22 @@ public enum GatewayResultCode implements ResultCode { ...@@ -47,9 +51,22 @@ public enum GatewayResultCode implements ResultCode {
/** ip不允许访问 */ /** ip不允许访问 */
IP_NOT_ALLOW_ACCESS("IP_NOT_ALLOW_ACCESS", "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获取 * 初始化保存到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.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
public final class WebUtils {
private static final int CONNECT_TIMEOUT = Config.getHttpConnectTimeout();// 设置连接建立的超时时间为10s
private static final int SOCKET_TIMEOUT = Config.getHttpSocketTimeout();
private static final int MAX_CONN = Config.getHttpMaxPoolSize(); // 最大连接数
private static final int MAX_PRE_ROUTE = Config.getHttpMaxPoolSize();
private static final int MAX_ROUTE = Config.getHttpMaxPoolSize();
private static CloseableHttpClient httpClient; // 发送请求的客户端单例
private static PoolingHttpClientConnectionManager manager; // 连接池管理类
private static ScheduledExecutorService monitorExecutor;
private final static Object syncLock = new Object(); // 相当于线程锁,用于线程安全
/**
* http 请求
*
* @param url
* @param params
* @return
* @throws Exception
*/
public static String post(String url, Map<String, String> params) throws Exception {
CloseableHttpClient client = getHttpClient(url);
String responseText = "";
CloseableHttpResponse response = null;
try {
HttpPost method = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
method.setConfig(requestConfig);
if (params != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Entry<String, String> param : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
paramList.add(pair);
}
method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
}
response = client.execute(method, HttpClientContext.create());
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (null != response) {
response.close();
}
} catch (Exception e) {
throw e;
}
}
return responseText;
}
public static String post(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
CloseableHttpClient client = getHttpClient(url);
String responseText = "";
CloseableHttpResponse response = null;
try {
HttpPost method = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
method.setConfig(requestConfig);
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
method.setHeader(entry.getKey(), entry.getValue());
}
}
if (params != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Entry<String, String> param : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
paramList.add(pair);
}
method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
}
response = client.execute(method, HttpClientContext.create());
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (null != response) {
response.close();
}
} catch (Exception e) {
throw e;
}
}
return responseText;
}
/**
* 通过流方式传数据
*
* @param uri
* @param data
* @return
*/
public static String post(String uri, String data) {
CloseableHttpClient httpClient = getHttpClient(uri);
HttpPost method = new HttpPost(uri);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
method.setConfig(requestConfig);
String readContent = null;
try {
method.addHeader("Content-type", "application/xml; charset=ISO-8859-1");
method.setHeader("Accept", "application/xml");
method.setEntity(new StringEntity(data, Charset.forName("utf-8")));
HttpResponse response = httpClient.execute(method, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
return "failed";
}
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
int count = 0;
while (count == 0) {
count = Integer.parseInt("" + entity.getContentLength());// in.available();
}
if (count <= 0) {
return EntityUtils.toString(entity);
}
byte[] bytes = new byte[count];
int readCount = 0; // 已经成功读取的字节的个数
while (readCount <= count) {
if (readCount == count) {
break;
}
readCount += in.read(bytes, readCount, count - readCount);
}
readContent = new String(bytes, 0, readCount, "UTF-8");
log.info("Get Response Content():\n {}", readContent);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return readContent;
}
/**
* 验证码实时校验
* 无需cookie和referer时请求接口
*
* @param headers 请求头
* @param baseUrl 发送请求的URL
* @return URL 所代表远程资源的响应结果
*/
public static String doGet(String baseUrl, Map<String, String> headers) {
CloseableHttpClient httpClient = getHttpClient(baseUrl);
CloseableHttpResponse response = null;
String body = null;
try {
log.info("接口请求路径:" + baseUrl);
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;
}
/**
* 关闭连接池
*/
public static void closeConnectionPool() {
try {
httpClient.close();
manager.close();
monitorExecutor.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 把map转为xml
*
* @param parameters
* @return
*/
public static String parseXML(Map<String, String> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Iterator<Entry<String, String>> itor = parameters.entrySet().iterator();
while (itor.hasNext()) {
Entry<String, String> entry = itor.next();
String k = entry.getKey();
String v = entry.getValue();
if (null != v && !"".equals(v) && !"appkey".equals(k)) {
sb.append("<" + k + ">" + parameters.get(k) + "</" + k + ">\n");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 把map转为xml
*
* @param parameters
* @return
*/
public static String parseJSON(Map<String, String> parameters) {
return new JSONWriter().write(parameters);
}
/**
* 从URL中提取所有的参数。
*
* @param query URL地址
* @return 参数映射
*/
public static Map<String, String> splitUrlQuery(String query) {
Map<String, String> result = new HashMap<String, String>();
String[] pairs = query.split("&");
if (pairs != null && pairs.length > 0) {
for (String pair : pairs) {
String[] param = pair.split("=", 2);
if (param != null && param.length == 2) {
result.put(param[0], param[1]);
}
}
}
return result;
}
public static CloseableHttpClient getHttpClient(String url) {
int port = 80;
String hostName = url.split("/")[2];
if (hostName.contains(":")) {
String[] args = hostName.split(":");
hostName = args[0];
port = Integer.parseInt(args[1]);
}
if (httpClient == null) {
// 多线程下多个线程同时调用getHttpClient容易导致重复创建httpClient对象的问题,所以加上了同步锁
synchronized (syncLock) {
if (httpClient == null) {
httpClient = createHttpClient(hostName, port);
// 开启监控线程,对异常和空闲线程进行关闭
monitorExecutor = Executors.newScheduledThreadPool(1);
monitorExecutor.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// 关闭异常连接
manager.closeExpiredConnections();
// 关闭5s空闲的连接
manager.closeIdleConnections(Config.getHttpIdelTimeout(), TimeUnit.MILLISECONDS);
}
}, Config.getHttpMonitorInterval(), Config.getHttpMonitorInterval(), TimeUnit.MILLISECONDS);
}
}
}
return httpClient;
}
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;
}
/**
* 根据host和port构建httpclient实例
*
* @param host 要访问的域名
* @param port 要访问的端口
* @return
*/
public static CloseableHttpClient createHttpClient(String host, int port) {
ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory).register("https", sslSocketFactory).build();
manager = new PoolingHttpClientConnectionManager(registry);
// 设置连接参数
manager.setMaxTotal(MAX_CONN); // 最大连接数
manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE); // 路由最大连接数
HttpHost httpHost = new HttpHost(host, port);
manager.setMaxPerRoute(new HttpRoute(httpHost), MAX_ROUTE);
// 请求失败时,进行请求重试
HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
if (i > 3) {
// 重试超过3次,放弃请求
log.error("retry has more than 3 time, give up request");
return false;
}
if (e instanceof NoHttpResponseException) {
// 服务器没有响应,可能是服务器断开了连接,应该重试
log.error("receive no response from server, retry");
return true;
}
if (e instanceof SSLHandshakeException) {
// SSL握手异常
log.error("SSL hand shake exception");
return false;
}
if (e instanceof InterruptedIOException) {
// 超时
log.error("InterruptedIOException");
return false;
}
if (e instanceof UnknownHostException) {
// 服务器不可达
log.error("server host unknown");
return false;
}
if (e instanceof ConnectTimeoutException) {
// 连接超时
log.error("Connection Time out");
return false;
}
if (e instanceof SSLException) {
log.error("SSLException");
return false;
}
HttpClientContext context = HttpClientContext.adapt(httpContext);
HttpRequest request = context.getRequest();
if (!(request instanceof HttpEntityEnclosingRequest)) {
// 如果请求不是关闭连接的请求
return true;
}
return false;
}
};
return HttpClients.custom().setConnectionManager(manager).setRetryHandler(handler).build();
}
}
class Config {
static int httpConnectTimeout = 3000;
static int httpSocketTimeout = 60000;
static int httpMaxPoolSize = 2000;
static int httpMonitorInterval = 3000;
static int httpIdelTimeout = 2000;
public static int getHttpIdelTimeout() {
return httpIdelTimeout;
}
public static int getHttpSocketTimeout() {
return httpSocketTimeout;
}
public static int getHttpMaxPoolSize() {
return httpMaxPoolSize;
}
public static int getHttpMonitorInterval() {
return httpMonitorInterval;
}
public static int getHttpConnectTimeout() {
return httpConnectTimeout;
}
}
package com.jz.dm.filter; 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.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.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse; 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 org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/** /**
* @author ZC * @author ZC
* @PACKAGE_NAME: com.jz.dm.filter * @PACKAGE_NAME: com.jz.dm.filter
...@@ -15,8 +36,20 @@ import org.springframework.stereotype.Component; ...@@ -15,8 +36,20 @@ import org.springframework.stereotype.Component;
* @Description: 认证过滤器 * @Description: 认证过滤器
**/ **/
@Component("authFilter") @Component("authFilter")
@Slf4j
public class AuthFilter extends AbstractFilter { 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 @Override
public String getFilterName() { public String getFilterName() {
...@@ -27,10 +60,89 @@ public class AuthFilter extends AbstractFilter { ...@@ -27,10 +60,89 @@ public class AuthFilter extends AbstractFilter {
public int getOrder() { public int getOrder() {
return Constants.FILTER_ORDER_5; 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); 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; 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.exception.GatewayException;
import com.jz.dm.common.util.SignType; import com.jz.dm.common.util.SignType;
import com.jz.dm.common.util.StringUtil; 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.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse; 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 org.springframework.stereotype.Component;
import java.nio.charset.Charset;
/** /**
* 参数检查过滤器 * 参数检查过滤器
* *
...@@ -22,7 +20,7 @@ public class CheckArgsFilter extends AbstractFilter { ...@@ -22,7 +20,7 @@ public class CheckArgsFilter extends AbstractFilter {
@Override @Override
public int getOrder() { public int getOrder() {
return Constants.FILTER_ORDER_3; return Constants.FILTER_ORDER_2;
} }
@Override @Override
...@@ -34,23 +32,20 @@ public class CheckArgsFilter extends AbstractFilter { ...@@ -34,23 +32,20 @@ public class CheckArgsFilter extends AbstractFilter {
FilterChain chain) { FilterChain chain) {
// 校验参数非空 // 校验参数非空
if (StringUtil.isEmpty(request.getAppKey()) || StringUtil.isEmpty(request.getMethod()) if (StringUtil.isEmpty(request.getAppKey()) || StringUtil.isEmpty(request.getMethod())
|| StringUtil.isEmpty(request.getCharset()) || StringUtil.isEmpty(request.getSignType()) || StringUtil.isEmpty(request.getSignType())|| StringUtil.isEmpty(request.getSign())
|| StringUtil.isEmpty(request.getSign()) || StringUtil.isEmpty(request.getTimestamp()) || StringUtil.isEmpty(request.getTimestamp())|| StringUtil.isEmpty(request.getParams())) {
|| StringUtil.isEmpty(request.getVersion()) throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT); //无效参数
|| StringUtil.isEmpty(request.getParams())) {
//无效参数
throw new GatewayException(GatewayResultCode.ILLEGAL_ARGUMENT);
} }
// 设置默认值 // 设置默认值
if (StringUtil.isEmpty(request.getFormat())) { if (StringUtil.isEmpty(request.getFormat())) {
request.setFormat(Format.JSON.name()); request.setFormat(Format.JSON.name());
} }
try { try {
request.setVersion("v1.0.0");
//格式,目前仅支持JSON //格式,目前仅支持JSON
Format.valueOf(request.getFormat()); Format.valueOf(request.getFormat());
//请求使用的编码格式,如UTF-8,GBK,GB2312等 //请求使用的编码格式,如UTF-8,GBK,GB2312等
Charset.forName(request.getCharset()); //Charset.forName(request.getCharset());
//生成签名字符串所使用的签名算法类型 //生成签名字符串所使用的签名算法类型
SignType.valueOf(request.getSignType()); SignType.valueOf(request.getSignType());
} catch (Exception ex) { } catch (Exception ex) {
......
...@@ -2,14 +2,13 @@ package com.jz.dm.filter; ...@@ -2,14 +2,13 @@ package com.jz.dm.filter;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; 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.Constants;
import com.jz.dm.common.constant.LoggingConstants; import com.jz.dm.common.constant.LoggingConstants;
import com.jz.dm.common.util.LogUtil;
import com.jz.dm.gateway.DefaultOpenApiDispatcher; import com.jz.dm.gateway.DefaultOpenApiDispatcher;
import com.jz.dm.models.enity.*; import com.jz.dm.models.enity.DispatchContext;
import com.jz.dm.common.enums.GatewayResultCode; import com.jz.dm.models.enity.GatewayRequest;
import com.jz.dm.common.enums.RouteType; import com.jz.dm.models.enity.GatewayResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -45,19 +44,17 @@ public class InvokeRouteFilter extends AbstractFilter { ...@@ -45,19 +44,17 @@ public class InvokeRouteFilter extends AbstractFilter {
//当前系统时间戳 //当前系统时间戳
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
try { try {
OpenApi openApi = (OpenApi) RequestContext.getCurrentContext().get("openApi"); //OpenApi openApi = (OpenApi) RequestContext.getCurrentContext().get("openApi");
if (openApi.getRouteType() == null) { //if (openApi.getRouteType() == null) {
throw new GatewayException(GatewayResultCode.ILLEGAL_ROUTE_TYPE); // throw new GatewayException(GatewayResultCode.ILLEGAL_ROUTE_TYPE);
} //}
if (openApi.getRouteType() != RouteType.SRPING) { //if (openApi.getRouteType() != RouteType.SRPING) {
chain.doFilter(request, response); // chain.doFilter(request, response);
return; // return;
} //}
DispatchContext context = new DispatchContext(); DispatchContext context = new DispatchContext();
context.setAppKey(request.getAppKey());//apiKey context.setAppKey(request.getAppKey());//apiKey
context.setApplication(openApi.getApplication());//应用
//context.setApplication(openApi.getApplication());//应用
context.setOpenApiMethod(request.getMethod()); //方法 例如:tradd.add context.setOpenApiMethod(request.getMethod()); //方法 例如:tradd.add
context.setOpenApiParams(request.getParams());//入参 context.setOpenApiParams(request.getParams());//入参
context.setOpenApiVersion(request.getVersion()); //版本号 context.setOpenApiVersion(request.getVersion()); //版本号
......
package com.jz.dm.filter; package com.jz.dm.filter;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.common.constant.Constants; 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.GatewayRequest;
import com.jz.dm.models.enity.GatewayResponse; import com.jz.dm.models.enity.GatewayResponse;
import com.jz.dm.models.enity.OpenApi; import com.jz.dm.service.ApiInterfaceService;
import com.jz.dm.models.enity.RequestContext;
import com.jz.dm.common.enums.RouteType;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List;
import java.util.TreeMap;
/** /**
* 验签过滤器(验证签名信息) * 验签过滤器(验证签名信息)
*/ */
...@@ -16,9 +26,11 @@ import org.springframework.stereotype.Component; ...@@ -16,9 +26,11 @@ import org.springframework.stereotype.Component;
@Component @Component
public class VerifySignFilter extends AbstractFilter { public class VerifySignFilter extends AbstractFilter {
@Autowired
private ApiInterfaceService apiInterfaceService;
@Override @Override
public int getOrder() { public int getOrder() {
return Constants.FILTER_ORDER_2; return Constants.FILTER_ORDER_3;
} }
@Override @Override
...@@ -28,11 +40,35 @@ public class VerifySignFilter extends AbstractFilter { ...@@ -28,11 +40,35 @@ public class VerifySignFilter extends AbstractFilter {
@Override @Override
protected void internalDoFilter(GatewayRequest request, GatewayResponse response, protected void internalDoFilter(GatewayRequest request, GatewayResponse response,
FilterChain chain) { 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 openApi = new OpenApi();
openApi.setApplication("JZ_API_GATEWAY");//应用 //openApi.setApplication("JZ_API_GATEWAY");//应用
openApi.setRouteType(RouteType.SRPING);//漏油类型 //openApi.setRouteType(RouteType.SRPING);//漏油类型
RequestContext.getCurrentContext().set("openApi", openApi); //RequestContext.getCurrentContext().set("openApi", openApi);
chain.doFilter(request, response); chain.doFilter(request, response);
} }
......
package com.jz.dm.models.enity; package com.jz.dm.models.enity;
import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -7,6 +9,7 @@ import java.util.Map; ...@@ -7,6 +9,7 @@ import java.util.Map;
/** /**
* Dispatch Context * Dispatch Context
*/ */
@Data
public class DispatchContext implements Serializable { public class DispatchContext implements Serializable {
/** /**
...@@ -15,15 +18,10 @@ public class DispatchContext implements Serializable { ...@@ -15,15 +18,10 @@ public class DispatchContext implements Serializable {
private static final long serialVersionUID = -3448256355423553719L; private static final long serialVersionUID = -3448256355423553719L;
/** /**
* 商户应用id * api唯一标识
*/ */
private String appKey; private String appKey;
/**
* 应用
*/
private String application;
/** /**
* openapi接口 * openapi接口
*/ */
...@@ -44,95 +42,6 @@ public class DispatchContext implements Serializable { ...@@ -44,95 +42,6 @@ public class DispatchContext implements Serializable {
*/ */
private final Map<String, Object> extAttributes = new HashMap<String, Object>(); 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 { ...@@ -169,7 +78,7 @@ public class DispatchContext implements Serializable {
*/ */
@Override @Override
public String toString() { public String toString() {
return "DispatchContext [application=" + application + ", openApiMethod=" + openApiMethod return "DispatchContext [openApiMethod=" + openApiMethod
+ ", openApiParams=" + openApiParams + ", openApiVersion=" + openApiVersion + "]"; + ", openApiParams=" + openApiParams + ", openApiVersion=" + openApiVersion + "]";
} }
......
...@@ -2,6 +2,9 @@ package com.jz.dm.models.enity; ...@@ -2,6 +2,9 @@ package com.jz.dm.models.enity;
import com.jz.dm.web.annotation.ParamName; 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.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
...@@ -9,261 +12,46 @@ import java.util.Map; ...@@ -9,261 +12,46 @@ import java.util.Map;
/** /**
* api请求 * api请求
* * @author zc
* @author ZC
*/ */
@ApiModel("api请求实体类")
@Data
public class GatewayRequest implements Serializable { public class GatewayRequest implements Serializable {
/**
* 分配的ID
*/
@ParamName("app_key") @ParamName("app_key")
@ApiModelProperty(value = "appKey API唯一标识")
private String appKey; private String appKey;
/** @ApiModelProperty(value = "接口名称")
* 接口名称
*/
private String method; private String method;
/** @ApiModelProperty(value = "格式,目前仅支持JSON")
* 格式,目前仅支持JSON
*/
private String format; private String format;
/** /**
* 请求使用的编码格式,如UTF-8,GBK,GB2312等 * 请求使用的编码格式,如UTF-8,GBK,GB2312等
*/ */
private String charset; //private String charset;
/**
* 生成签名字符串所使用的签名算法类型
*/
@ParamName("sign_type") @ParamName("sign_type")
@ApiModelProperty(value = "生成签名字符串所使用的签名算法类型")
private String signType; private String signType;
/** @ApiModelProperty(value = "请求参数的签名串")
* 请求参数的签名串
*/
private String sign; private String sign;
/** @ApiModelProperty(value = "发送请求的时间,格式yyyy-MM-dd HH:mm:ss")
* 发送请求的时间,格式"yyyy-MM-dd HH:mm:ss"
*/
private String timestamp; private String timestamp;
/** @ApiModelProperty(value="调用的接口版本,固定为:1.0")
* 调用的接口版本,固定为:1.0
*/
private String version; private String version;
/** @ApiModelProperty(value="请求参数,JSON格式")
* 请求参数,JSON格式
*/
private String params; private String params;
/** @ApiModelProperty(value="扩展属性")
* 扩展属性
*/
private final Map<String, Attribute> extAttributes = new HashMap<String, Attribute>(); 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 { ...@@ -301,7 +89,7 @@ public class GatewayRequest implements Serializable {
@Override @Override
public String toString() { public String toString() {
return "GatewayRequest [appKey=" + appKey + ", method=" + method + ", format=" + format return "GatewayRequest [appKey=" + appKey + ", method=" + method + ", format=" + format
+ ", charset=" + charset + ", signType=" + signType + ", sign=" + sign + ", signType=" + signType + ", sign=" + sign
+ ", timestamp=" + timestamp + ", version=" + version + ", timestamp=" + timestamp + ", version=" + version
+ ", params=" + params + ", extAttributes=" + ", params=" + params + ", extAttributes="
+ 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; package com.jz.dm.service;
import com.jz.common.utils.Result; import com.jz.common.utils.Result;
import com.jz.dm.models.domian.ApiAuth;
import com.jz.dm.models.req.auth.*; import com.jz.dm.models.req.auth.*;
/** /**
...@@ -54,4 +55,11 @@ public interface AuthService { ...@@ -54,4 +55,11 @@ public interface AuthService {
* @return * @return
*/ */
Result updateSaltInfo(SaltResetReq req); Result updateSaltInfo(SaltResetReq req);
/**
* 获取API授权信息
* @param authCode
* @return
*/
ApiAuth getAuthUser( String authCode);
} }
...@@ -52,4 +52,11 @@ public interface OrganizationManageService { ...@@ -52,4 +52,11 @@ public interface OrganizationManageService {
* @return * @return
*/ */
Result delete(Long id); 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 { ...@@ -264,6 +264,19 @@ public class AuthServiceImpl implements AuthService {
return Result.of_success(ResultMsg.UPDATE_FAIL); 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) { private ApiInterface getInterface(String apiKey) {
QueryWrapper<ApiInterface> queryInface = new QueryWrapper<>(); QueryWrapper<ApiInterface> queryInface = new QueryWrapper<>();
queryInface.last("where is_deleted=0 and api_key ='" + apiKey + "'"); queryInface.last("where is_deleted=0 and api_key ='" + apiKey + "'");
......
...@@ -184,6 +184,19 @@ public class OrganizationManageImpl implements OrganizationManageService { ...@@ -184,6 +184,19 @@ public class OrganizationManageImpl implements OrganizationManageService {
return Result.of_success(ResultMsg.DELETE_FAIL); 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; ...@@ -9,6 +9,7 @@ import com.jz.common.bean.SysUserDto;
import com.jz.common.constant.RedisMessageConstant; import com.jz.common.constant.RedisMessageConstant;
import com.jz.common.constant.ResultMsg; import com.jz.common.constant.ResultMsg;
import com.jz.common.exception.ResponseException; import com.jz.common.exception.ResponseException;
import com.jz.common.utils.HttpsUtils;
import com.jz.common.utils.RedisUtils; import com.jz.common.utils.RedisUtils;
import com.jz.common.utils.Result; import com.jz.common.utils.Result;
import com.jz.dm.common.constant.TagConstants; import com.jz.dm.common.constant.TagConstants;
...@@ -16,7 +17,6 @@ import com.jz.dm.common.enums.GeneralStatusTypeEnum; ...@@ -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.apiInterface.ApiStatusEnum;
import com.jz.dm.common.enums.produce.ProducerStatusTypeEnum; import com.jz.dm.common.enums.produce.ProducerStatusTypeEnum;
import com.jz.dm.common.util.RandomUtil; import com.jz.dm.common.util.RandomUtil;
import com.jz.dm.common.util.WebUtils;
import com.jz.dm.mapper.*; import com.jz.dm.mapper.*;
import com.jz.dm.models.domian.*; import com.jz.dm.models.domian.*;
import com.jz.dm.models.req.make.*; import com.jz.dm.models.req.make.*;
...@@ -66,6 +66,8 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -66,6 +66,8 @@ public class ProducerServiceImpl implements ProducerService {
private RedisTemplate<String, Object> redisTemplate; private RedisTemplate<String, Object> redisTemplate;
@Autowired @Autowired
private RedisUtils redisUtils; private RedisUtils redisUtils;
@Autowired
private HttpsUtils httpsUtils;
@Value("${dmp.openapi.timeout.max}") @Value("${dmp.openapi.timeout.max}")
private int maxTimeout; private int maxTimeout;
...@@ -413,7 +415,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -413,7 +415,7 @@ public class ProducerServiceImpl implements ProducerService {
} }
JSONArray result = new JSONArray(); JSONArray result = new JSONArray();
log.info("查询es标签类下的索引地址信息:" + datasource.getJdbcUrl() + "/es/get/indicess"); 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) { if (resp != null) {
log.info("返回索引信息集合:" + resp); log.info("返回索引信息集合:" + resp);
JSONArray json = JSONArray.parseArray(resp); JSONArray json = JSONArray.parseArray(resp);
...@@ -450,7 +452,7 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -450,7 +452,7 @@ public class ProducerServiceImpl implements ProducerService {
JSONObject param = new JSONObject(); JSONObject param = new JSONObject();
param.put("indices", indices); param.put("indices", indices);
log.info("参数集合:" + param.toString()); 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); log.info("索引下type的信息集合:" + resp);
return Result.of_success(resp); return Result.of_success(resp);
} }
...@@ -473,12 +475,12 @@ public class ProducerServiceImpl implements ProducerService { ...@@ -473,12 +475,12 @@ public class ProducerServiceImpl implements ProducerService {
HashMap<String, String> herders = new HashMap<>(); HashMap<String, String> herders = new HashMap<>();
herders.put("Content-Encoding", "UTF-8"); herders.put("Content-Encoding", "UTF-8");
herders.put("Content-Type", "application/json"); herders.put("Content-Type", "application/json");
HashMap<String, String> dataMap = new HashMap<>(); JSONObject param = new JSONObject();
dataMap.put("indices", indices); param.put("indices", indices);
dataMap.put("type", type); param.put("type", type);
String resp = null; String resp = null;
try { 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); log.info("索引下type的fields信息集合:" + resp);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); 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.OpenApiRequest;
import com.jz.dm.common.util.OpenApiResponse; import com.jz.dm.common.util.OpenApiResponse;
import com.jz.dm.gateway.OpenApiService; 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.AccessLimit;
import com.jz.dm.web.annotation.ApiLogAspect; import com.jz.dm.web.annotation.ApiLogAspect;
import lombok.extern.slf4j.Slf4j; 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.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
/** /**
* @author ZC * @author ZC
* @PACKAGE_NAME: com.jz.dm.service.apirequest * @PACKAGE_NAME: com.jz.dm.service.request
* @PROJECT_NAME: jz-dm-parent * @PROJECT_NAME: jz-dm-parent
* @NAME: ApiQueryService * @NAME: ApiQueryService
* @DATE: 2020-12-23/18:10 * @DATE: 2020-12-23/18:10
...@@ -29,14 +34,42 @@ public class ApiQueryService implements OpenApiService { ...@@ -29,14 +34,42 @@ public class ApiQueryService implements OpenApiService {
@Override @Override
public String getOpenApiVersion() { public String getOpenApiVersion() {
return "1.0.0"; return "v1.0.0";
} }
@Autowired
private ApiInterfaceService apiInterfaceService;
@Override @Override
@ApiLogAspect @ApiLogAspect(description = "API请求日志")
@AccessLimit(limit = 10000,sec = 1) @AccessLimit(limit = 10000,sec = 1)
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW) @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
public void doService(OpenApiRequest request, OpenApiResponse response) { 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: ...@@ -83,3 +83,6 @@ dmp:
timeout: timeout:
default: 5000 default: 5000
max: 5000 max: 5000
request:
limit:
max: 10
package com.jz.dm.gateway.orther; 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.gateway.SpringTestCase;
import com.jz.dm.service.ProducerService; import com.jz.dm.service.ProducerService;
import org.junit.Test; 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 @@ ...@@ -3,6 +3,7 @@
*/ */
package com.jz.common.utils; package com.jz.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript; import org.springframework.data.redis.core.script.RedisScript;
...@@ -20,6 +21,7 @@ import java.util.concurrent.TimeUnit; ...@@ -20,6 +21,7 @@ import java.util.concurrent.TimeUnit;
* @version $Id: RedisUtils.java 2019年11月2日 上午8:36:41 $ * @version $Id: RedisUtils.java 2019年11月2日 上午8:36:41 $
*/ */
@Component("redisUtils") @Component("redisUtils")
@Slf4j
public class RedisUtils { public class RedisUtils {
@Autowired @Autowired
private RedisTemplate<String, Object> redisTemplate; private RedisTemplate<String, Object> redisTemplate;
...@@ -238,4 +240,21 @@ public class RedisUtils { ...@@ -238,4 +240,21 @@ public class RedisUtils {
return redisTemplate.opsForList().range(key, 0, 500); 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