Prechádzať zdrojové kódy

fix:eos修复文件上传接口

lllgodenough 1 rok pred
rodič
commit
fb275787f6

+ 3 - 3
application.yaml

@@ -16,8 +16,8 @@ spring:
     redis:
       # 【移动云】redis内网IPV4地址,内网 IPv4数据端口:30010,【不知这里需不需要申请分配公网IPv6地址???】
       host: 8.130.28.19
-      port: 30010
-      password: 123456@Eai
+      port: 6378
+      password: eai123456
   mail:
     host: smtp.163.com
     port: 25
@@ -102,8 +102,8 @@ xunfei:
 
 deepseek:
   api:
-    key: E-OYKpcDb_L5WjdVPw2sZ-08ds4Vv-hBRe-lAV9tnqI
     base-url: https://zhenze-huhehaote.cmecloud.cn/v1/chat/completions
+    key: E-OYKpcDb_L5WjdVPw2sZ-08ds4Vv-hBRe-lAV9tnqI
     model: deepseek-v3
     temperature: 0.7
 

+ 45 - 9
src/main/java/com/njuzr/eaibackend/config/ECloudEosConfig.java

@@ -1,5 +1,6 @@
 package com.njuzr.eaibackend.config;
 
+import com.amazonaws.ClientConfiguration;
 import com.amazonaws.auth.AWSCredentials;
 import com.amazonaws.auth.AWSCredentialsProvider;
 import com.amazonaws.auth.AWSStaticCredentialsProvider;
@@ -7,6 +8,7 @@ import com.amazonaws.auth.BasicAWSCredentials;
 import com.amazonaws.client.builder.AwsClientBuilder;
 import com.amazonaws.services.s3.AmazonS3;
 import com.amazonaws.services.s3.AmazonS3ClientBuilder;
+import org.springframework.beans.factory.DisposableBean;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.context.properties.ConfigurationProperties;
 import org.springframework.context.annotation.Bean;
@@ -17,24 +19,52 @@ import org.springframework.context.annotation.Configuration;
  * @date 2025/9/14 - 14:31
  */
 @Configuration
-public class ECloudEosConfig {
-    public String getBucketName() {
-        return bucketName;
-    }
+public class ECloudEosConfig implements DisposableBean {
+
+    private static volatile AmazonS3 eosClientInstance;
 
     @Value("${ecloud.eos.endpoint}")
     private String endpoint;
+
     @Value("${ecloud.eos.region}")
     private String region;
+
     @Value("${ecloud.eos.access-key}")
     private String accessKey;
+
     @Value("${ecloud.eos.secret-key}")
     private String secretKey;
+
     @Value("${ecloud.eos.bucket-name}")
     private String bucketName;
 
-    @Bean
-    public AmazonS3 EosClient() {
+    public String getBucketName() {
+        return bucketName;
+    }
+
+    public String getEndpoint() {
+        return this.endpoint;
+    }
+
+    @Bean(destroyMethod = "shutdown")
+    public AmazonS3 eosClient() {
+        if (eosClientInstance == null) {
+            synchronized (ECloudEosConfig.class) {
+                if (eosClientInstance == null) {
+                    eosClientInstance = createEosClient();
+                }
+            }
+        }
+        return eosClientInstance;
+    }
+
+    private AmazonS3 createEosClient() {
+        // 配置客户端超时参数
+        ClientConfiguration clientConfig = new ClientConfiguration();
+        clientConfig.setConnectionTimeout(10000); // 连接超时:10秒
+        clientConfig.setSocketTimeout(600000);    // 读取超时:10分钟
+        clientConfig.setMaxErrorRetry(3);         // 失败自动重试3次
+
         // 配置端点
         AwsClientBuilder.EndpointConfiguration endpointConfiguration =
                 new AwsClientBuilder.EndpointConfiguration(
@@ -55,10 +85,16 @@ public class ECloudEosConfig {
         return AmazonS3ClientBuilder.standard()
                 .withEndpointConfiguration(endpointConfiguration)
                 .withCredentials(credentialsProvider)
+                .withClientConfiguration(clientConfig)
                 .build();
     }
 
-    public String getEndpoint() {
-        return this.endpoint;
+    @Override
+    public void destroy() throws Exception {
+        // 显式销毁客户端
+        if (eosClientInstance != null) {
+            eosClientInstance.shutdown();
+            eosClientInstance = null;
+        }
     }
-}
+}

+ 15 - 26
src/main/java/com/njuzr/eaibackend/controller/FileController.java

@@ -1,13 +1,11 @@
 package com.njuzr.eaibackend.controller;
 
+import com.amazonaws.AmazonServiceException;
 import com.amazonaws.HttpMethod;
 import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
 import com.amazonaws.services.s3.model.ObjectListing;
-import com.amazonaws.services.s3.model.ObjectMetadata;
-import com.amazonaws.services.s3.model.PutObjectResult;
 import com.njuzr.eaibackend.config.ECloudEosConfig;
 import com.njuzr.eaibackend.exception.MyException;
-import com.njuzr.eaibackend.utils.OssUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
@@ -20,8 +18,7 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import java.util.UUID;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
+
 
 /**
  * @author: Leonezhurui
@@ -39,40 +36,32 @@ public class FileController {
 
 
     @PostMapping
-    public CompletableFuture<MyResponse> upload(@RequestParam("file") MultipartFile file) {
-        return CompletableFuture.supplyAsync(() -> {
+    public MyResponse upload(@RequestParam("file") MultipartFile file) {
             String filePath = "uploads/" + UUID.randomUUID() + file.getOriginalFilename();
-            ObjectMetadata metadata = new ObjectMetadata();
-            metadata.setContentLength(file.getSize());
-            metadata.setContentType(file.getContentType());
-            metadata.setHeader("original-filename", file.getOriginalFilename());
-
             try (InputStream inputStream = file.getInputStream()) {
-                eCloudEosConfig.EosClient().putObject(eCloudEosConfig.getBucketName(), filePath, inputStream, metadata);
-                Date expiration = new Date();
-                expiration.setTime(expiration.getTime() + 1000L * 60 * 1000);
-
+                eCloudEosConfig.eosClient().putObject(eCloudEosConfig.getBucketName(), filePath, inputStream, null);
                 GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(eCloudEosConfig.getBucketName(), filePath)
                         .withMethod(HttpMethod.GET)
-                        .withExpiration(expiration);
-                URL presignedUrl = eCloudEosConfig.EosClient().generatePresignedUrl(request);
+                        .withExpiration(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000));
+
+                URL presignedUrl = eCloudEosConfig.eosClient().generatePresignedUrl(request);
                 String url = presignedUrl.toString();
                 log.info("文件上传成功: {}, url: {}", filePath, url);
                 return MyResponse.success(url);
-            } catch (IOException e) {
-                throw new MyException(500, "上传文件失败");
+            } catch (AmazonServiceException e) {
+                // 这是服务端返回的错误(如权限不足、Bucket不存在等)
+                log.error("EOS服务端处理请求失败。错误信息: {}", e.getMessage());
+                throw new MyException(500, "云存储服务异常: " + e.getErrorMessage());
+            }catch (IOException e) {
+                log.error("EOS服务端处理请求失败。错误信息: {}", e.getMessage());
+                throw new MyException(500, "上传文件失败" + e.getMessage());
             }
-        }).completeOnTimeout(
-                MyResponse.error(400,"文件上传超时,请稍后再试"),
-                300,  // 超时时间(秒)
-                TimeUnit.SECONDS
-        );
     }
 
     @GetMapping
     public MyResponse getFiles() {
         // 列出存储桶中的对象
-        ObjectListing objectListing = eCloudEosConfig.EosClient().listObjects(eCloudEosConfig.getBucketName());
+        ObjectListing objectListing = eCloudEosConfig.eosClient().listObjects(eCloudEosConfig.getBucketName());
         List<String> files = new ArrayList<>();
         objectListing.getObjectSummaries().forEach(objectSummary -> {
             files.add(objectSummary.getKey());

+ 1 - 1
src/main/java/com/njuzr/eaibackend/service/DeepSeekService.java

@@ -40,7 +40,6 @@ public class DeepSeekService {
 
     public String chatCompletion(List<AIEntry> message) throws IOException {
         HttpPost httpPost = new HttpPost(deepSeekConfig.getBaseUrl());
-        System.out.println(httpPost.getURI());
         // 设置请求头
         httpPost.setHeader("Content-Type", "application/json");
         httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey());
@@ -52,6 +51,7 @@ public class DeepSeekService {
         requestBody.put("temperature", deepSeekConfig.getTemperature());
 
         StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
+        System.out.println("请求体:" + entity.getContent().toString());
         httpPost.setEntity(entity);
 
         // 执行请求

+ 1 - 1
src/test/java/com/njuzr/eaibackend/EaiBackendApplicationTests.java

@@ -41,7 +41,7 @@ class EaiBackendApplicationTests {
         }
 
         // 列出存储桶中的对象
-        ObjectListing objectListing = eCloudEosConfig.EosClient().listObjects(eCloudEosConfig.getBucketName());
+        ObjectListing objectListing = eCloudEosConfig.eosClient().listObjects(eCloudEosConfig.getBucketName());
         List<String> files = new ArrayList<>();
         objectListing.getObjectSummaries().forEach(objectSummary -> {
             System.out.println(objectSummary.getKey());