Pārlūkot izejas kodu

优化RequestUtil读取属性方法

Signed-off-by: luoshi <luoshi@qmth.com.cn>
luoshi 2 gadi atpakaļ
vecāks
revīzija
3e142bc3ac

+ 3 - 3
starter-api/src/main/java/com/qmth/boot/api/interceptor/impl/MetricsInterceptor.java

@@ -32,9 +32,9 @@ public class MetricsInterceptor extends AbstractInterceptor implements ApiConsta
     }
 
     private long getTimecost(HttpServletRequest request) {
-        Object startTime = request.getAttribute(ATTRIBUTE_START_TIME);
-        if (startTime instanceof Long) {
-            return System.currentTimeMillis() - (Long) startTime;
+        Long startTime = RequestUtil.getAttribute(request, ApiConstant.ATTRIBUTE_START_TIME);
+        if (startTime != null) {
+            return System.currentTimeMillis() - startTime;
         } else {
             return -1;
         }

+ 14 - 20
starter-api/src/main/java/com/qmth/boot/api/utils/RequestUtil.java

@@ -10,11 +10,9 @@ public class RequestUtil implements ApiConstant {
     private static final String FIELD_IP = "_IP_";
 
     public static String getIpAddress(HttpServletRequest request) {
-        Object obj = request.getAttribute(FIELD_IP);
-        if (obj instanceof String) {
-            return (String) obj;
-        } else {
-            String ip = request.getHeader("X-FORWARDED-FOR");
+        String ip = getAttribute(request, FIELD_IP);
+        if (StringUtils.isEmpty(ip)) {
+            ip = request.getHeader("X-FORWARDED-FOR");
             if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                 ip = request.getHeader("X-Real-IP");
             }
@@ -36,28 +34,24 @@ public class RequestUtil implements ApiConstant {
                 ip = ip.split(",")[0];
             }
             request.setAttribute(FIELD_IP, ip);
-            return ip;
         }
+        return ip;
     }
 
-    public static <T> T getAttribute(HttpServletRequest request, String name) {
+    public static <T> T getAttribute(HttpServletRequest request, String name, T defaultValue) {
         Object obj = request.getAttribute(name);
-        try {
-            return (T) obj;
-        } catch (Exception e) {
-            return null;
+        T value = null;
+        if (obj != null) {
+            try {
+                value = (T) obj;
+            } catch (Exception ignored) {
+            }
         }
+        return value != null ? value : defaultValue;
     }
 
-    public static String getAttribute(HttpServletRequest request, String name, String defaultValue) {
-        Object obj = request.getAttribute(name);
-        if (obj instanceof String) {
-            return (String) obj;
-        } else if (defaultValue != null) {
-            return defaultValue;
-        } else {
-            return null;
-        }
+    public static <T> T getAttribute(HttpServletRequest request, String name) {
+        return getAttribute(request, name, null);
     }
 
 }