Selaa lähdekoodia

修复一些问题

ximinghao 1 kuukausi sitten
vanhempi
sitoutus
c2c914023f

+ 15 - 1
pom.xml

@@ -42,6 +42,10 @@
             <artifactId>httpclient5</artifactId>
             <version>5.3.1</version>
         </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-gateway-mvc</artifactId>
+        </dependency>
         <!--            打包专用,平时注释掉-->
         <dependency>
             <groupId>javax.servlet</groupId>
@@ -197,7 +201,17 @@
             <version>3.8.0</version>
         </dependency>
     </dependencies>
-
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.cloud</groupId>
+                <artifactId>spring-cloud-dependencies</artifactId>
+                <version>2021.0.6</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
     <build>
         <plugins>
             <plugin>

+ 0 - 1
src/main/java/com/skyversation/xjcy/bean/ClueFollow.java

@@ -1,7 +1,6 @@
 package com.skyversation.xjcy.bean;
 
 import com.alibaba.fastjson.annotation.JSONField;
-import com.skyversation.xjcy.config.LocalDateFromTimestampDeserializer;
 import com.skyversation.xjcy.util.LocalDateTimeFromTimestampDeserializer;
 import lombok.Data;
 

+ 2 - 0
src/main/java/com/skyversation/xjcy/config/CorsConfig.java

@@ -1,5 +1,6 @@
 package com.skyversation.xjcy.config;
 
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.cors.CorsConfiguration;
@@ -12,6 +13,7 @@ import java.util.Collections;
 public class CorsConfig {
 
     @Bean
+    @ConditionalOnProperty(prefix = "app.cors", name = "enabled", havingValue = "true")
     public CorsFilter corsFilter() {
         CorsConfiguration corsConfiguration = new CorsConfiguration();
         // 设置允许跨域请求的域名

+ 86 - 0
src/main/java/com/skyversation/xjcy/controller/ProxyController.java

@@ -0,0 +1,86 @@
+package com.skyversation.xjcy.controller;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.DefaultResponseErrorHandler;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import javax.servlet.http.HttpServletRequest;
+import java.net.URI;
+
+@RestController
+@RequestMapping("/proxy")
+@Slf4j
+public class ProxyController {
+    @Value("${app.ows.path}")
+    private String geoServerPath;
+
+    private final RestTemplate restTemplate = restTemplate();
+
+    public RestTemplate restTemplate() {
+        RestTemplate restTemplate = new RestTemplate();
+        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
+            @Override
+            protected boolean hasError(HttpStatus statusCode) {
+                return false;  // 任何状态码都当成成功,把控制权交还给调用方
+            }
+        });
+        return restTemplate;
+    }
+
+//    @GetMapping("/geoserver/**")
+//    public ResponseEntity<?> proxyGeoserver(ProxyExchange<byte[]> proxy, @RequestParam Map<String,String> queryParams) throws Exception {
+//        String remainingPath = proxy.path("/proxy/geoserver/");
+//
+//        // 构建完整目标 URI
+//        String targetBase = geoServerPath + "/" + remainingPath;  // 注意 geoServerPath 不要以 / 结尾
+//        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(targetBase);
+//        MultiValueMap<String, String> queryParam = new LinkedMultiValueMap<>();
+//        queryParams.forEach(queryParam::add);
+//        builder.queryParams(queryParam);
+//        URI finalUri = builder.build().toUri();
+//
+//        // 打印最终转发的 URL(用于调试)
+//        System.out.println("Forwarding to: " + finalUri.toString());
+//
+//        // 执行转发
+//        return proxy.uri(finalUri).get();
+//    }
+
+    @GetMapping("/geoserver/**")
+    public String proxyGeoserver(HttpServletRequest request,
+                                                 @RequestParam MultiValueMap<String, String> queryParams) throws Exception {
+
+        // 1. 提取 /geoserver/ 之后的剩余路径
+        String prefix = "/geoserver/";
+        String requestURI = request.getRequestURI();
+        int index = requestURI.indexOf(prefix);
+        String remainingPath = index >= 0 ? requestURI.substring(index + prefix.length()) : "";
+
+        // 2. 构建目标 URL
+        String targetBase = geoServerPath + "/" + remainingPath;   // geoServerPath 不要以 / 结尾
+        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(targetBase);
+        if (queryParams != null && !queryParams.isEmpty()) {
+            builder.queryParams(queryParams);
+        }
+        URI finalUri = builder.build().toUri();
+
+        log.info("Forwarding to: {}", finalUri.toString());
+
+        // 3. 服务端自行发起 GET 请求,并直接返回目标服务的响应体
+        ResponseEntity<String> response = restTemplate.exchange(
+                finalUri, HttpMethod.GET, null,String.class);
+
+        // 保留目标服务返回的状态码和关键头(特别是 Content-Type),只返回 body
+        return response.getBody();
+    }
+}

+ 9 - 12
src/main/java/com/skyversation/xjcy/service/OWSService.java

@@ -4,6 +4,8 @@ import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.skyversation.xjcy.util.HttpUtil;
 import lombok.Getter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -18,6 +20,7 @@ import java.util.Map;
 
 @Service
 public class OWSService {
+    private static final Logger log = LoggerFactory.getLogger(OWSService.class);
     @Value("${app.ows.path}")
     private String owsPath;
 
@@ -38,29 +41,23 @@ public class OWSService {
         }
     }
 
-    private JSONArray sendToOWS(Map<String, String> params, int depth) {
+    private JSONArray sendToOWS(Map<String, String> params) {
         MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
         for (Map.Entry<String, String> entry : params.entrySet()) {
             map.add(entry.getKey(), entry.getValue());
         }
         try {
-            String result = HttpUtil.requestGet(owsPath, map, Collections.emptyMap());
+            String result = HttpUtil.requestGet(owsPath+"/xjxm/ows", map, Collections.emptyMap());
             JSONObject json = JSONObject.parseObject(result);
             return json.getJSONArray("features");
         } catch (RestClientException e) {
-            if (depth >= 3) {
-                System.out.println("无法访问OWS服务,相关参数如下");
-                System.out.println("path:"+owsPath);
-                params.forEach((k,v)-> System.out.println(k+":"+v));
-                return null;
-            }
-            return sendToOWS(params, depth + 1);
+            log.error("无法访问OWS服务,相关参数如下");
+            log.error("path:{}/xjxm/ows", owsPath);
+            params.forEach((k,v)-> log.error("{}:{}", k, v));
+            return null;
         }
     }
 
-    private JSONArray sendToOWS(Map<String, String> params) {
-        return sendToOWS(params, 0);
-    }
 
     private Map<String, String> commonParams() {
         Map<String, String> params = new HashMap<String, String>();

+ 6 - 2
src/main/resources/application.yml

@@ -15,6 +15,8 @@ spring:
       max-file-size: 3000MB
       max-request-size: 3000MB
 logging:
+  file:
+    name: /var/log/xjcy/xjcy.log
   level:
     org:
       springframework:
@@ -35,7 +37,7 @@ app:
     path: ${OAUTH_LOGIN_PATH:http://121.43.55.7:10086/oauth}
     role-config: '{"ENTERPRISE_ROLE":[{"roleId":"40","serviceId":"11","comment":"企业用户权限,pc端"},{"roleId":"44","serviceId":"12","comment":"企业用户权限,wx小程序端"}],"INIT_ROLE":[{"roleId":"41","serviceId":"11","comment":"普通游客权限,pc端"},{"roleId":"45","serviceId":"12","comment":"普通游客权限,wx小程序端"},{"roleId":"48","serviceId":"2","comment":"徐泾一般用户,dms"}]}'
   ows:
-    path: ${OWS_PATH:http://121.43.55.7:8889/geoserver/xjxm/ows}
+    path: ${OWS_PATH:http://121.43.55.7:8889/geoserver}
   wechat:
     appid: ${XJCY_WECHAT_APPID:wx125843453562c86c}
     secret-key: ${XJCY_WECHAT_SECRET:6028cc345cfdbc76224d750a13519762}
@@ -62,6 +64,8 @@ app:
         template-code: ${XJCY_ALIBABA_NOTICE_TEMPLATE:SMS_500695141}
     ocr:
       endpoint: ${ALIBABA_CLOUD_OCR_ENDPOINT:ocr-api.cn-hangzhou.aliyuncs.com}
+  cors:
+    enabled: ${CORS_ENABLED:true}
 ---
 spring:
   config:
@@ -81,7 +85,7 @@ app:
   execute-startup-tasks: false
   external:
     service:
-#      url: ${EXTERNAL_SERVICE_URL:http://127.0.0.1:10022/xjcy-external}
+      url: ${EXTERNAL_SERVICE_URL:http://127.0.0.1:10022/xjcy-external}
 #  wechat:
 #    appid: ${XJCY_WECHAT_APPID:wx125843453562c86c}
 #    secret-key: ${XJCY_WECHAT_SECRET:6028cc345cfdbc76224d750a13519762}