Przeglądaj źródła

fix: 个人库相关功能

liaoyitao 5 miesięcy temu
rodzic
commit
a230ae2ed3

+ 1 - 1
src/main/java/com/lqkj/link/config/ThreadPoolConfig.java

@@ -14,7 +14,7 @@ public class ThreadPoolConfig {
14 14
         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
15 15
         executor.setCorePoolSize(20); // 核心线程池大小
16 16
         executor.setMaxPoolSize(50); // 最大线程池大小
17
-        executor.setQueueCapacity(150); // 队列容量
17
+        executor.setQueueCapacity(500); // 队列容量
18 18
         executor.setThreadNamePrefix("Async-"); // 线程名称前缀
19 19
         executor.initialize();
20 20
         return executor;

+ 4 - 0
src/main/java/com/lqkj/link/module/authority/service/UserInfoService.java

@@ -3,6 +3,7 @@ package com.lqkj.link.module.authority.service;
3 3
 import com.lqkj.link.module.authority.domain.UserInfo;
4 4
 import com.lqkj.link.module.authority.repository.RoleInfoRepository;
5 5
 import com.lqkj.link.module.authority.repository.UserInfoRepository;
6
+import com.lqkj.link.util.FileUtils;
6 7
 import jakarta.annotation.PostConstruct;
7 8
 import org.springframework.transaction.annotation.Transactional;
8 9
 import org.apache.commons.lang3.StringUtils;
@@ -12,6 +13,7 @@ import org.springframework.data.domain.Pageable;
12 13
 import org.springframework.security.crypto.password.PasswordEncoder;
13 14
 import org.springframework.stereotype.Service;
14 15
 
16
+import java.io.File;
15 17
 import java.util.*;
16 18
 import java.util.regex.Matcher;
17 19
 import java.util.regex.Pattern;
@@ -176,4 +178,6 @@ public class UserInfoService {
176 178
     public void resourceRefreshed(String userCode) {
177 179
         userInfoRepository.resourceRefreshed();
178 180
     }
181
+
182
+
179 183
 }

+ 8 - 0
src/main/java/com/lqkj/link/module/base/service/BaseService.java

@@ -88,4 +88,12 @@ public class BaseService {
88 88
             throw new RuntimeException(e);
89 89
         }
90 90
     }
91
+
92
+    public String ossAddModel(MultipartFile file, String s) {
93
+        try {
94
+            return aliOSSUtils.addModel(file, s);
95
+        } catch (Exception e) {
96
+            throw new RuntimeException(e);
97
+        }
98
+    }
91 99
 }

+ 30 - 0
src/main/java/com/lqkj/link/module/zone/controller/ResourceController.java

@@ -249,4 +249,34 @@ public class ResourceController {
249 249
     public MessageBean<String> ossUpload(MultipartFile file) {
250 250
         return MessageBean.ok(baseService.ossUpload(file), "oss上传");
251 251
     }
252
+
253
+    @GetMapping("/checkCapacity")
254
+    public MessageBean<String> checkCapacity(HttpServletRequest request){
255
+        String authHeader = request.getHeader("Authorization");
256
+        String userCode = jwtService.decryptUsernameWithHeader(authHeader);
257
+        return MessageBean.ok(resourceService.checkCapacity(userCode), "检查容量");
258
+    }
259
+
260
+    @Operation(
261
+            summary = "个人库模型上传接口",
262
+            description = "个人库模型上传接口",
263
+            parameters = {
264
+                    @Parameter(name = "file", description = "文件", required = true)
265
+            }
266
+    )
267
+    @PostMapping("/oss/addModel")
268
+    public MessageBean<String> ossAddModel(MultipartFile file,
269
+                                        HttpServletRequest request) {
270
+        String authHeader = request.getHeader("Authorization");
271
+        String userCode = jwtService.decryptUsernameWithHeader(authHeader);
272
+        Integer userId = userInfoService.detailByUserCode(userCode).getUserId();
273
+        return MessageBean.ok(baseService.ossAddModel(file, "resource/model/" + userId + "/"), "oss上传");
274
+    }
275
+
276
+    @GetMapping("/oss/checkCapacity")
277
+    public MessageBean<String> ossCheckCapacity(HttpServletRequest request){
278
+        String authHeader = request.getHeader("Authorization");
279
+        String userCode = jwtService.decryptUsernameWithHeader(authHeader);
280
+        return MessageBean.ok(resourceService.ossCheckCapacity(userCode), "检查容量");
281
+    }
252 282
 }

+ 15 - 0
src/main/java/com/lqkj/link/module/zone/service/ResourceService.java

@@ -7,6 +7,7 @@ import com.lqkj.link.module.zone.domain.ModelInfo;
7 7
 import com.lqkj.link.module.zone.repository.ModelCategoryRepository;
8 8
 import com.lqkj.link.module.zone.repository.ModelInfoRepository;
9 9
 import com.lqkj.link.util.AliOSSUtils;
10
+import com.lqkj.link.util.FileUtils;
10 11
 import com.lqkj.link.util.Unzipper;
11 12
 import org.apache.commons.compress.archivers.ArchiveException;
12 13
 import org.springframework.beans.factory.annotation.Autowired;
@@ -164,4 +165,18 @@ public class ResourceService {
164 165
         UserInfo userInfo = userInfoRepository.findByUserCode(userCode);
165 166
         return userInfo.getRefreshResource() != null && userInfo.getRefreshResource();
166 167
     }
168
+
169
+    public String checkCapacity(String userCode) {
170
+        UserInfo userInfo = userInfoRepository.findByUserCode(userCode);
171
+        String filePath = "./upload/resource/model/" + userInfo.getUserId();
172
+        File file = new File(filePath);
173
+        if (!file.exists()) return "0";
174
+        return "个人库 已使用" + FileUtils.convertBytes(FileUtils.getFolderSize(new File(filePath))) + "/20G";
175
+    }
176
+
177
+    public String ossCheckCapacity(String userCode) {
178
+        UserInfo userInfo = userInfoRepository.findByUserCode(userCode);
179
+        Long aLong = aliOSSUtils.ossCheckCapacity("resource/model/" + userInfo.getUserId() + "/");
180
+        return "个人库 已使用" + FileUtils.convertBytes(aLong) + "/20G";
181
+    }
167 182
 }

+ 54 - 1
src/main/java/com/lqkj/link/util/AliOSSUtils.java

@@ -2,6 +2,9 @@ package com.lqkj.link.util;
2 2
 
3 3
 import com.aliyun.oss.OSS;
4 4
 import com.aliyun.oss.OSSClientBuilder;
5
+import com.aliyun.oss.model.ListObjectsV2Request;
6
+import com.aliyun.oss.model.ListObjectsV2Result;
7
+import com.aliyun.oss.model.OSSObjectSummary;
5 8
 import org.springframework.beans.factory.annotation.Autowired;
6 9
 import org.springframework.stereotype.Component;
7 10
 import org.springframework.web.multipart.MultipartFile;
@@ -13,6 +16,7 @@ import java.io.InputStream;
13 16
 import java.time.LocalDate;
14 17
 import java.time.LocalDateTime;
15 18
 import java.time.LocalTime;
19
+import java.util.List;
16 20
 import java.util.UUID;
17 21
 import java.util.concurrent.Callable;
18 22
 
@@ -38,6 +42,11 @@ public class AliOSSUtils {
38 42
         String originalFilename = file.getName();
39 43
         String fileName = "file/" + LocalDate.now() + "/" + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
40 44
         //上传文件到 OSS
45
+        try {
46
+            Thread.sleep(200);
47
+        } catch (InterruptedException e) {
48
+            throw new RuntimeException(e);
49
+        }
41 50
         OSS ossClient = new OSSClientBuilder().build(aliProperties.getEndpoint(), aliProperties.getAccessKeyId(), aliProperties.getAccessKeySecret());
42 51
         threadPoolUtil.getTaskExecutor().execute(() -> {
43 52
             ossClient.putObject(aliProperties.getBucketName(), fileName, file);
@@ -70,5 +79,49 @@ public class AliOSSUtils {
70 79
         }
71 80
     }
72 81
 
73
- 
82
+
83
+    public String addModel(MultipartFile file, String path) {
84
+        // 获取上传的文件的输入流
85
+        try {
86
+            InputStream inputStream = file.getInputStream();
87
+            // 避免文件覆盖
88
+            String originalFilename = file.getOriginalFilename();
89
+            String fileName = path + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
90
+            //上传文件到 OSS
91
+            OSS ossClient = new OSSClientBuilder().build(aliProperties.getEndpoint(), aliProperties.getAccessKeyId(), aliProperties.getAccessKeySecret());
92
+            threadPoolUtil.getTaskExecutor().execute(() -> {
93
+                ossClient.putObject(aliProperties.getBucketName(), fileName, inputStream);
94
+                ossClient.shutdown();
95
+            });
96
+            //文件访问路径
97
+            return aliProperties.getOsspath().split("//")[0] + "//" + aliProperties.getBucketName() + "." + aliProperties.getOsspath().split("//")[1] + "/" + fileName;
98
+        } catch (IOException e) {
99
+            throw new RuntimeException(e);
100
+        }
101
+    }
102
+
103
+    public Long ossCheckCapacity(String path) {
104
+        OSS ossClient = new OSSClientBuilder().build(aliProperties.getEndpoint(), aliProperties.getAccessKeyId(), aliProperties.getAccessKeySecret());
105
+        return calculateFolderLength(ossClient, aliProperties.getBucketName(), path);
106
+    }
107
+
108
+    private static long calculateFolderLength(OSS ossClient, String bucketName, String folder) {
109
+        long size = 0L;
110
+        ListObjectsV2Result result = null;
111
+        do {
112
+            // MaxKey默认值为100,最大值为1000。
113
+            ListObjectsV2Request request = new ListObjectsV2Request(bucketName).withPrefix(folder).withMaxKeys(1000);
114
+            if (result != null) {
115
+                request.setContinuationToken(result.getNextContinuationToken());
116
+            }
117
+            result = ossClient.listObjectsV2(request);
118
+            List<OSSObjectSummary> sums = result.getObjectSummaries();
119
+            for (OSSObjectSummary s : sums) {
120
+                size += s.getSize();
121
+            }
122
+        } while (result.isTruncated());
123
+        return size;
124
+    }
125
+
126
+
74 127
 }

+ 45 - 0
src/main/java/com/lqkj/link/util/FileUtils.java

@@ -179,4 +179,49 @@ public class FileUtils {
179 179
         }
180 180
         return result;
181 181
     }
182
+
183
+    public static long getFolderSize(File folder) {
184
+        long totalSize = 0;
185
+
186
+        // 检查路径是否存在且为目录
187
+        if (folder.exists() && folder.isDirectory()) {
188
+            File[] files = folder.listFiles();
189
+            if (files != null) { // 处理可能为 null 的情况
190
+                for (File file : files) {
191
+                    if (file.isFile()) {
192
+                        // 累加文件大小
193
+                        totalSize += file.length();
194
+                    } else if (file.isDirectory()) {
195
+                        // 递归计算子目录大小
196
+                        totalSize += getFolderSize(file);
197
+                    }
198
+                }
199
+            }
200
+        } else {
201
+            System.out.println("The specified path does not exist or is not a directory.");
202
+        }
203
+
204
+        return totalSize;
205
+    }
206
+
207
+    public static String convertBytes(long bytes) {
208
+        if (bytes < 0) {
209
+            return "Invalid size";
210
+        }
211
+
212
+        // 定义单位
213
+        String[] units = {"B", "KB", "MB", "GB"};
214
+        int unitIndex = 0;
215
+
216
+        // 逐步转换为更大的单位
217
+        double size = (double) bytes;
218
+
219
+        while (unitIndex < units.length - 1) {
220
+            size /= 1024;
221
+            unitIndex++;
222
+        }
223
+
224
+        // 使用 String.format 格式化输出
225
+        return String.format("%.2f%s", size, units[unitIndex]);
226
+    }
182 227
 }