Commit de675214d231941a37fdc4872383f66d0acd71c7

Authored by 谭毅彬
1 parent d4fa895c

第三调用API接口请求路径统一以/api/wms/开头。OKHttpUtils优化请求参数,添加重试机制,细化日志输出。

Signed-off-by: TanYibin <5491541@qq.com>
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/api/acs/controller/AcsController.java
... ... @@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.*;
16 16 import io.swagger.annotations.ApiOperation;
17 17  
18 18 @RestController
19   -@RequestMapping("/API/WMS/acs")
  19 +@RequestMapping("/api/wms/acs")
20 20 public class AcsController extends HuahengBaseController {
21 21  
22 22 @Resource
... ...
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/api/erp/controller/ErpController.java
... ... @@ -24,7 +24,7 @@ import org.springframework.web.bind.annotation.RestController;
24 24 * @author 游杰
25 25 */
26 26 @RestController
27   -@RequestMapping("/API/WMS/erp")
  27 +@RequestMapping("/api/wms/erp")
28 28 public class ErpController extends HuahengBaseController {
29 29  
30 30 @Resource
... ...
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/api/mes/controller/MesController.java
... ... @@ -26,7 +26,7 @@ import org.springframework.web.bind.annotation.RestController;
26 26 * @author 游杰
27 27 */
28 28 @RestController
29   -@RequestMapping("/API/WMS/mes")
  29 +@RequestMapping("/api/wms/mes")
30 30 public class MesController extends HuahengBaseController {
31 31  
32 32 @Resource
... ...
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/api/wcs/controller/WcsController.java
... ... @@ -24,7 +24,7 @@ import org.springframework.web.bind.annotation.*;
24 24 import io.swagger.annotations.ApiOperation;
25 25  
26 26 @RestController
27   -@RequestMapping("/API/WMS/v2")
  27 +@RequestMapping("/api/wms/v2")
28 28 public class WcsController extends HuahengBaseController {
29 29  
30 30 @Resource
... ...
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/framework/aspectj/ApiLogAspect.java
... ... @@ -10,6 +10,7 @@ import org.aspectj.lang.annotation.Around;
10 10 import org.aspectj.lang.annotation.Aspect;
11 11 import org.aspectj.lang.annotation.Pointcut;
12 12 import org.aspectj.lang.reflect.MethodSignature;
  13 +import org.jeecg.JeecgSystemApplication;
13 14 import org.jeecg.common.api.vo.Result;
14 15 import org.jeecg.modules.wms.config.address.entity.Address;
15 16 import org.jeecg.modules.wms.config.address.service.IAddressService;
... ... @@ -101,7 +102,7 @@ public class ApiLogAspect {
101 102 String body = null;
102 103  
103 104 try {
104   - HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
  105 +// HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
105 106 connection = (HttpURLConnection)point.getArgs()[0];
106 107 body = (String)point.getArgs()[1];
107 108 initApiLog(connection, body);
... ... @@ -155,17 +156,18 @@ public class ApiLogAspect {
155 156  
156 157 /**
157 158 * 根据url,从address表中判断调用的去向
158   - **/
  159 + */
159 160 public static void parseUrl(ApiLog log, URL url, String warehouseCode) {
160 161 try {
161 162 String[] spList = url.toString().split("/");
162 163 String apiName = spList[spList.length - 1];
163   - int index = url.toString().lastIndexOf(apiName);
164   - String addUrl = url.toString().substring(0, index);
165   -
  164 +// int index = url.toString().lastIndexOf(apiName);
  165 +// String addUrl = url.toString().substring(0, index);
  166 + String ip = JeecgSystemApplication.getLocalHostExactAddress().getHostAddress();
166 167 Address address = addressService.getAddressByUrl(url.toString(), warehouseCode);
167 168 log.setApiName(apiName);
168 169 log.setRequestFrom("WMS");
  170 + log.setIp(ip);
169 171 log.setResponseBy(address.getParam().toUpperCase());
170 172 } catch (Exception e) {
171 173 e.printStackTrace();
... ... @@ -174,16 +176,16 @@ public class ApiLogAspect {
174 176  
175 177 /**
176 178 * 记录WMS调用外接口的请求信息
177   - * 在HttpUtils.bodypost方法中直接调用本类static方法
  179 + * 在HttpUtils.body POST方法中直接调用本类static方法
178 180 **/
179   - public static ApiLog initApiLog(String Method, String url, String body, HttpHeaders headers, String warehouseCode) {
  181 + public static ApiLog initApiLog(String Method, String urlStr, String body, HttpHeaders headers, String warehouseCode) {
180 182 ApiLog log = new ApiLog();
181 183 try {
182   - URL url1 = new URL(url);
  184 + URL url = new URL(urlStr);
183 185 log.setApiMethod(Method);
184   - log.setUrl(url);
  186 + log.setUrl(urlStr);
185 187 log.setRequestTime(new Date());
186   - parseUrl(log, url1, warehouseCode);
  188 + parseUrl(log, url, warehouseCode);
187 189  
188 190 // 请求头
189 191 Set<String> keySet = headers.keySet();
... ... @@ -206,7 +208,7 @@ public class ApiLogAspect {
206 208  
207 209 /**
208 210 * 记录WMS调用外接口的请求信息
209   - * 在HttpUtils.bodypost方法中直接调用本类static方法
  211 + * 在HttpUtils.body POST方法中直接调用本类static方法
210 212 **/
211 213 public static ApiLog initApiLog(HttpURLConnection connection, String body) {
212 214 ApiLog log = new ApiLog();
... ... @@ -223,7 +225,7 @@ public class ApiLogAspect {
223 225 while (it.hasNext()) {
224 226 String name = it.next();
225 227 String header = connection.getRequestProperty(name);
226   - headerList.add(name + ": " + header);
  228 + headerList.add(name + ":" + header);
227 229 }
228 230  
229 231 log.setRequestHeader(org.apache.commons.lang3.StringUtils.join(headerList, "\n"));
... ... @@ -278,10 +280,10 @@ public class ApiLogAspect {
278 280 } finally {
279 281 try {
280 282 if (StringUtils.isNotEmpty(log.getResponseBody()) && log.getResponseBody().length() > 2001) {
281   - log.setResponseBody(log.getResponseBody().substring(0, 2000) + "\n太长了...后面省略。\n" + log.getResponseBody().length());
  283 + log.setResponseBody(log.getResponseBody().substring(0, 2000) + "...\nResponseBodyLength:" + log.getResponseBody().length());
282 284 }
283 285 } catch (Exception e) {
284   -
  286 + e.printStackTrace();
285 287 }
286 288 SpringUtils.getBean(ApiLogAspect.class).saveApiLog(log);
287 289 }
... ... @@ -292,12 +294,13 @@ public class ApiLogAspect {
292 294 try {
293 295 String[] spList = url.toString().split("/");
294 296 String apiName = spList[spList.length - 1];
295   - int index = url.toString().lastIndexOf(apiName);
296   - String addUrl = url.toString().substring(0, index);
297   -
  297 +// int index = url.toString().lastIndexOf(apiName);
  298 +// String addUrl = url.toString().substring(0, index);
  299 + String ip = JeecgSystemApplication.getLocalHostExactAddress().getHostAddress();
298 300 Address address = addressService.getAddressByUrl(url.toString(), QuantityConstant.DEFAULT_WAREHOUSE);
299 301 log.setApiName(apiName);
300 302 log.setRequestFrom("WMS");
  303 + log.setIp(ip);
301 304 log.setResponseBy(address.getParam().toUpperCase());
302 305 } catch (Exception e) {
303 306 e.printStackTrace();
... ...
huaheng-wms-core/src/main/java/org/jeecg/modules/wms/framework/controller/TestController.java
... ... @@ -11,6 +11,7 @@ import org.jeecg.common.api.vo.Result;
11 11 import org.jeecg.common.aspect.annotation.AutoLog;
12 12 import org.jeecg.modules.system.entity.SysDataLog;
13 13 import org.jeecg.modules.system.service.ISysDataLogService;
  14 +import org.jeecg.modules.wms.framework.aspectj.lang.annotation.ApiLogger;
14 15 import org.jeecg.utils.HuahengRedisUtil;
15 16 import org.springframework.beans.factory.annotation.Autowired;
16 17 import org.springframework.transaction.annotation.Transactional;
... ... @@ -33,7 +34,6 @@ import lombok.extern.slf4j.Slf4j;
33 34 */
34 35 @Slf4j
35 36 @RestController
36   -@RequestMapping("/test")
37 37 public class TestController extends HuahengBaseController {
38 38  
39 39 @Autowired
... ... @@ -41,10 +41,21 @@ public class TestController extends HuahengBaseController {
41 41  
42 42 @Autowired
43 43 private ISysDataLogService sysDataLogService;
  44 +
  45 +
  46 + @ApiLogger(apiName = "API接口第三方Token校验测试", from = "TEST")
  47 + @ResponseBody
  48 + @PostMapping(value = "/api/wms/testTokenCheck")
  49 + public Result<?> testTokenCheck(@RequestBody Map<String, String> paramMap, HttpServletRequest request) {
  50 +
  51 +
  52 + return new Result<>();
  53 + }
  54 +
44 55  
45 56 @AutoLog(value = "TestController-testRedis")
46 57 @ResponseBody
47   - @PostMapping(value = "/testRedis")
  58 + @PostMapping(value = "/test/testRedis")
48 59 public Result<?> testRedis(@RequestBody Map<String, String> paramMap, HttpServletRequest request) {
49 60  
50 61 // log.info("testRedis in paramMap:{}", JSON.toJSONString(paramMap));
... ...
huaheng-wms-core/src/main/java/org/jeecg/utils/HuahengJwtUtil.java
... ... @@ -60,7 +60,7 @@ public class HuahengJwtUtil {
60 60 }
61 61  
62 62 /**
63   - * 生成签名,5min后过期
  63 + * 生成签名
64 64 * @param username 用户名
65 65 * @param secret 用户的密码
66 66 * @return 加密的token
... ... @@ -73,7 +73,7 @@ public class HuahengJwtUtil {
73 73 }
74 74  
75 75 /**
76   - * 生成签名,5min后过期
  76 + * 生成签名
77 77 * @param username 用户名
78 78 * @param secret 用户的密码
79 79 * @param warehouseCode 登录仓库
... ... @@ -98,5 +98,4 @@ public class HuahengJwtUtil {
98 98 return null;
99 99 }
100 100 }
101   -
102 101 }
... ...
huaheng-wms-core/src/main/java/org/jeecg/utils/http/OkHttpUtils.java
1 1 package org.jeecg.utils.http;
2 2  
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.alibaba.fastjson.TypeReference;
3 5 import com.alibaba.fastjson.parser.Feature;
4   -import com.google.gson.Gson;
5 6 import okhttp3.*;
6 7 import org.jeecg.modules.wms.framework.aspectj.ApiLogAspect;
7 8 import org.jeecg.modules.wms.monitor.apiLog.entity.ApiLog;
... ... @@ -15,6 +16,8 @@ import java.util.Map;
15 16 import java.util.Objects;
16 17 import java.util.concurrent.TimeUnit;
17 18  
  19 +import javax.validation.constraints.NotNull;
  20 +
18 21 /**
19 22 * OkHttp发送请求
20 23 * @author huaheng
... ... @@ -25,9 +28,25 @@ public class OkHttpUtils {
25 28 private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);
26 29  
27 30 /**
28   - * 最大连接时间
  31 + * 最多重试次数
  32 + */
  33 + public final static int MAX_RENTRY_COUNT = 3;
  34 +
  35 + /**
  36 + * 最大连接时间(秒)
29 37 */
30   - public final static int CONNECTION_TIMEOUT = 30;
  38 + public final static int CONNECTION_TIMEOUT = 1;
  39 +
  40 + /**
  41 + * 最大读取时间(秒)
  42 + */
  43 + public final static int READ_TIMEOUT = 30;
  44 +
  45 + /**
  46 + * 最大写入时间(秒)
  47 + */
  48 + public final static int WRITE_TIMEOUT = 30;
  49 +
31 50 /**
32 51 * JSON格式
33 52 */
... ... @@ -44,18 +63,16 @@ public class OkHttpUtils {
44 63 private static final String CONTENT_TYPE = "Content-Type";
45 64  
46 65 /**
47   - * client
48   - * 配置重试
  66 + * client 配置重试
49 67 */
50   - private final static OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder().readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
51   - .writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS).connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
52   - .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES)).build();
53   - private static final Gson GSON = new Gson();
  68 + private final static OkHttpClient HTTP_CLIENT =
  69 + new OkHttpClient.Builder().connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS).readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
  70 + .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).addInterceptor(new OkHttpUtils.OkhttpInterceptor(MAX_RENTRY_COUNT)) // 过滤器,设置最大重试次数
  71 + .retryOnConnectionFailure(false).connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES)).build();
54 72  
55 73 /**
56 74 * 向指定 URL 发送GET方法的请求
57   - * @param url 发送请求的 URL
58   - * //* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  75 + * @param url 发送请求的 URL //* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
59 76 * @return 所代表远程资源的响应结果
60 77 */
61 78 public static String sendGet(String url, String param) {
... ... @@ -73,19 +90,18 @@ public class OkHttpUtils {
73 90 response = HTTP_CLIENT.newCall(request).execute();
74 91 if (response.isSuccessful() && Objects.nonNull(response.body())) {
75 92 String result = response.body().string();
76   - log.info("执行get请求, url: {} 成功,返回数据: {}", url, result);
  93 + log.info("执行GET请求,url:{},header:{},param:{} 成功,返回数据:{}", url, JSON.toJSONString(headers), param, result);
77 94 return result;
78 95 }
79 96 } catch (IOException e) {
80   - log.error("执行get请求,url: {} 失败!", url, e);
  97 + log.error("执行GET请求,url:{},header:{},param:{} 失败!", url, JSON.toJSONString(headers), param, e);
81 98 }
82 99 return "";
83 100 }
84 101  
85 102 /**
86 103 * 向指定 URL 发送POST方法的请求
87   - * @param url 发送请求的 URL
88   - * // * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  104 + * @param url 发送请求的 URL // * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
89 105 * @return 所代表远程资源的响应结果
90 106 */
91 107 public static String sendPost(String url, String param) {
... ... @@ -107,7 +123,7 @@ public class OkHttpUtils {
107 123 }
108 124  
109 125 // 此方法是将参数以body形式发送post请求
110   - public static String bodypost(String strURL, String json) {
  126 + public static String bodypost(String url, String json) {
111 127 ApiLog apiLog = null;
112 128 // using above json body as a input to post API call
113 129 RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
... ... @@ -117,7 +133,7 @@ public class OkHttpUtils {
117 133 headers.put("Content-Type", "application/json");// 设置发送数据的格式
118 134 Request.Builder builder = new Request.Builder();
119 135 buildHeader(builder, headers);
120   - Request request = builder.url(strURL).post(body).build();
  136 + Request request = builder.url(url).post(body).build();
121 137 Response response = null;
122 138 String result = null;
123 139 try {
... ... @@ -125,11 +141,11 @@ public class OkHttpUtils {
125 141 response = HTTP_CLIENT.newCall(request).execute();
126 142 if (response.isSuccessful() && Objects.nonNull(response.body())) {
127 143 result = response.body().string();
128   - log.info("执行post请求,url: {}, header: {} ,参数: {} 成功,返回结果: {}", strURL, headers, json, result);
  144 + log.info("执行POST请求,url:{},header:{},param:{} 成功,返回结果:{}", url, JSON.toJSONString(headers), json, result);
129 145 }
130 146 } catch (IOException e) {
131 147 ApiLogAspect.setApiLogException(apiLog, e);
132   - log.error("执行post请求,url: {},参数: {} 失败!", strURL, json, e);
  148 + log.error("执行POST请求,url:{},header:{},param:{} 失败!", url, JSON.toJSONString(headers), json, e);
133 149 } finally {
134 150 ApiLogAspect.finishApiLog(apiLog, response, result);
135 151 }
... ... @@ -163,12 +179,43 @@ public class OkHttpUtils {
163 179 * @param type 嵌套泛型
164 180 * @return 响应对象, 可进行强转。
165 181 */
166   - public static <T> T post(String url, String json, Type type) {
  182 + public static <T> T post(String url, String json, TypeReference<T> type) {
167 183 String result = bodypost(url, json);
168 184 if (Objects.nonNull(result) && Objects.nonNull(type)) {
169   - return GSON.fromJson(result, type);
  185 + return JSON.parseObject(result, type);
170 186 }
171 187 return null;
172 188 }
173 189  
  190 + public static class OkhttpInterceptor implements Interceptor {
  191 + // 最大重试次数
  192 + private int maxRentry;
  193 +
  194 + public OkhttpInterceptor(int maxRentry) {
  195 + this.maxRentry = maxRentry;
  196 + }
  197 +
  198 + @NotNull
  199 + @Override
  200 + public Response intercept(@NotNull Chain chain) throws IOException {
  201 + /*
  202 + * 递归 2次下发请求,如果仍然失败 则返回 null ,但是 intercept must not return null. 返回 null 会报 IllegalStateException 异常
  203 + */
  204 + return retry(chain, 0);
  205 + }
  206 +
  207 + private Response retry(Chain chain, int retryCent) {
  208 + Request request = chain.request();
  209 + Response response = null;
  210 + try {
  211 + response = chain.proceed(request);
  212 + } catch (Exception e) {
  213 + if (maxRentry > retryCent) {
  214 + return retry(chain, retryCent + 1);
  215 + }
  216 + }
  217 + return response;
  218 + }
  219 + }
  220 +
174 221 }
... ...
huaheng-wms-core/src/main/resources/application-dev.yml
... ... @@ -191,7 +191,7 @@ jeecg:
191 191 #webapp文件路径
192 192 webapp: /opt/webapp
193 193 shiro:
194   - excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**,/sys/getWarehouseByUserCode,/test/test**
  194 + excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**,/sys/getWarehouseByUserCode,/test/test**,/api/wms/**
195 195 #阿里云oss存储和大鱼短信秘钥配置
196 196 oss:
197 197 accessKey: ??
... ...
huaheng-wms-core/src/main/resources/application-prod.yml
... ... @@ -189,7 +189,7 @@ jeecg:
189 189 #webapp文件路径
190 190 webapp: /opt/jeecg-boot/webapp
191 191 shiro:
192   - excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**,/api/getUserInfo
  192 + excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**,/sys/getWarehouseByUserCode,/test/test**,/api/wms/**
193 193 #阿里云oss存储和大鱼短信秘钥配置
194 194 oss:
195 195 accessKey: ??
... ...
huaheng-wms-core/src/main/resources/application-test.yml
... ... @@ -191,7 +191,7 @@ jeecg:
191 191 #webapp文件路径
192 192 webapp: /opt/webapp
193 193 shiro:
194   - excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**,/sys/getWarehouseByUserCode,/test/test**
  194 + excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**,/sys/getWarehouseByUserCode,/test/test**,/api/wms/**
195 195 #阿里云oss存储和大鱼短信秘钥配置
196 196 oss:
197 197 accessKey: ??
... ... @@ -277,6 +277,7 @@ logging:
277 277 org.jeecg.common: WARN
278 278 org.jeecg.modules: WARN
279 279 org.jeecg.modules.wms: DEBUG
  280 + org.jeecg.config.shiro: DEBUG
280 281 #swagger
281 282 knife4j:
282 283 #开启增强配置
... ...