diff --git a/web-api/ruoyi-common/src/main/java/com/ruoyi/common/utils/TencentCosUtil.java b/web-api/ruoyi-common/src/main/java/com/ruoyi/common/utils/TencentCosUtil.java index 1612c9e..5a27fde 100644 --- a/web-api/ruoyi-common/src/main/java/com/ruoyi/common/utils/TencentCosUtil.java +++ b/web-api/ruoyi-common/src/main/java/com/ruoyi/common/utils/TencentCosUtil.java @@ -13,6 +13,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -38,6 +41,19 @@ public class TencentCosUtil { @Value("${tencentCos.domain}") private String domain; + private COSClient cosClient; + + @PostConstruct + public void initCosClient() { + cosClient = createCosClient(); + } + + @PreDestroy + public void destroyCosClient() { + if (cosClient != null) { + cosClient.shutdown(); + } + } /** * 上传MultipartFile到腾讯云COS,返回文件访问地址 @@ -59,8 +75,6 @@ public class TencentCosUtil { throw new IllegalArgumentException("上传文件不能为空"); } - COSClient cosClient = createCosClient(); - // 生成唯一文件键,格式与AWS一致:yyyy/MM/dd/uuid_filename String key = generateCosKey(file.getOriginalFilename()); @@ -89,8 +103,6 @@ public class TencentCosUtil { } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("上传文件到COS失败: " + e.getMessage(), e); - } finally { - cosClient.shutdown(); } }