OssFileService.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package com.fdkankan.fyun.oss;
  2. import cn.hutool.core.collection.CollUtil;
  3. import com.aliyun.oss.HttpMethod;
  4. import com.aliyun.oss.OSS;
  5. import com.aliyun.oss.model.*;
  6. import com.fdkankan.fyun.constant.FYunTypeEnum;
  7. import com.fdkankan.fyun.face.AbstractFYunFileService;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.util.CollectionUtils;
  14. import org.springframework.util.ObjectUtils;
  15. import java.io.*;
  16. import java.net.URL;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.stream.Collectors;
  21. @Component
  22. @ConditionalOnProperty(name = "fyun.type", havingValue = "oss")
  23. public class OssFileService extends AbstractFYunFileService {
  24. private Logger log = LoggerFactory.getLogger(this.getClass().getName());
  25. @Autowired
  26. private OSS ossClient;
  27. @Override
  28. public String uploadFile(String bucket, byte[] data, String remoteFilePath) {
  29. try {
  30. ossClient.putObject(bucket, remoteFilePath, new ByteArrayInputStream(data));
  31. } catch (Exception e) {
  32. log.error("oss上传文件失败,remoteFilePath:" + remoteFilePath, e);
  33. }
  34. return null;
  35. }
  36. @Override
  37. public String uploadFile(String bucket, String filePath, String remoteFilePath) {
  38. return uploadFile(bucket, filePath, remoteFilePath, null);
  39. }
  40. @Override
  41. public String uploadFile(String bucket, InputStream inputStream, String remoteFilePath) {
  42. try {
  43. ossClient.putObject(bucket, remoteFilePath, inputStream);
  44. log.info("文件流上传成功,目标路径:remoteFilePath:{}", remoteFilePath);
  45. } catch (Exception e) {
  46. log.error("oss上传文件失败,remoteFilePath:"+remoteFilePath, e);
  47. }
  48. return null;
  49. }
  50. @Override
  51. public String uploadFile(String bucket, String filePath, String remoteFilePath, Map<String, String> headers) {
  52. try {
  53. File file = new File(filePath);
  54. if (!file.exists()) {
  55. log.warn("要上传的文件不存在,filePath" + filePath);
  56. return null;
  57. }
  58. ObjectMetadata metadata = new ObjectMetadata();
  59. if (filePath.contains(".jpg")) {
  60. metadata.setContentType("image/jpeg");
  61. }
  62. if (filePath.contains(".mp4")) {
  63. metadata.setContentType("video/mp4");
  64. }
  65. if (filePath.contains(".mp3")) {
  66. metadata.setContentType("audio/mp3");
  67. }
  68. if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(headers)) {
  69. for (Map.Entry<String, String> header : headers.entrySet()) {
  70. metadata.setHeader(header.getKey(), header.getValue());
  71. }
  72. }
  73. ossClient.putObject(bucket, remoteFilePath, file, metadata);
  74. log.info("文件上传成功,path:{}", filePath);
  75. } catch (Exception e) {
  76. log.error("oss上传文件失败,filePath:"+filePath, e);
  77. }
  78. return null;
  79. }
  80. @Override
  81. public String uploadFileByCommand(String bucket, String filePath, String remoteFilePath) {
  82. try {
  83. String optType = new File(filePath).isDirectory() ? "folder" : "file";
  84. String command = String.format(fYunConstants.UPLOAD_SH, bucket, filePath, remoteFilePath, FYunTypeEnum.OSS.code(), optType);
  85. log.info("开始上传文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  86. callshell(command);
  87. log.info("上传文件完毕, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  88. } catch (Exception e) {
  89. log.error(String.format("上传文件失败, ossPath:%s, srcPath:%s", remoteFilePath, filePath), e);
  90. }
  91. return null;
  92. }
  93. @Override
  94. public void downloadFileByCommand(String bucket, String filePath, String remoteFilePath) {
  95. try {
  96. String optType = remoteFilePath.contains(".") ? "file" : "folder";
  97. String command = String.format(fYunConstants.DOWNLOAD_SH, bucket, remoteFilePath, filePath, FYunTypeEnum.OSS.code(), optType);
  98. log.info("开始下载文件, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  99. callshell(command);
  100. log.info("下载文件完毕, ossPath:{}, srcPath:{}", remoteFilePath, filePath);
  101. } catch (Exception e) {
  102. log.error(String.format("下载文件失败, ossPath:%s, srcPath:%s", remoteFilePath, filePath), e);
  103. }
  104. }
  105. @Override
  106. public void deleteFile(String bucket, String remoteFilePath) throws IOException {
  107. try {
  108. ossClient.deleteObject(bucket, remoteFilePath);
  109. } catch (Exception e) {
  110. log.error("OSS删除文件失败,key:" + remoteFilePath, e);
  111. }
  112. }
  113. @Override
  114. public void deleteFolder(String bucket, String remoteFolderPath) {
  115. try {
  116. if (!remoteFolderPath.endsWith("/")) {
  117. remoteFolderPath = remoteFolderPath + "/";
  118. }
  119. log.info("开始删除文件夹:{}", remoteFolderPath);
  120. boolean flag = true;
  121. String nextMaker = null;
  122. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket).withPrefix(remoteFolderPath).withMaxKeys(1000);
  123. DeleteObjectsRequest request = new DeleteObjectsRequest(bucket);
  124. do {
  125. //获取下一页的起始点,它的下一项
  126. listObjectsRequest.setMarker(nextMaker);
  127. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  128. List<String> keys = objectListing.getObjectSummaries().parallelStream()
  129. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  130. if (!CollectionUtils.isEmpty(keys)) {
  131. request.setKeys(keys);
  132. ossClient.deleteObjects(request);
  133. }
  134. nextMaker = objectListing.getNextMarker();
  135. //全部执行完后,为false
  136. flag = objectListing.isTruncated();
  137. } while (flag);
  138. } catch (Exception e) {
  139. log.error("OSS删除文件失败,key:" + remoteFolderPath, e);
  140. }
  141. }
  142. @Override
  143. public void uploadMulFiles(String bucket, Map<String, String> filepaths) {
  144. try {
  145. for (Map.Entry<String, String> entry : filepaths.entrySet()) {
  146. uploadFile(bucket, entry.getKey(), entry.getValue(), null);
  147. }
  148. } catch (Exception e) {
  149. log.error("OSS批量上传文件失败!");
  150. }
  151. }
  152. @Override
  153. public List<String> listRemoteFiles(String bucket, String sourcePath) {
  154. List<String> keyList = new ArrayList<>();
  155. try {
  156. boolean flag = true;
  157. String nextMaker = null;
  158. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
  159. //指定下一级文件
  160. listObjectsRequest.setPrefix(sourcePath);
  161. //设置分页的页容量
  162. listObjectsRequest.setMaxKeys(200);
  163. do {
  164. //获取下一页的起始点,它的下一项
  165. listObjectsRequest.setMarker(nextMaker);
  166. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  167. List<String> collect = objectListing.getObjectSummaries().parallelStream()
  168. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  169. if (!CollectionUtils.isEmpty(collect)) {
  170. keyList.addAll(collect);
  171. }
  172. nextMaker = objectListing.getNextMarker();
  173. //全部执行完后,为false
  174. flag = objectListing.isTruncated();
  175. } while (flag);
  176. } catch (Exception e) {
  177. log.error("获取文件列表失败,path:" + sourcePath, e);
  178. }
  179. return keyList;
  180. }
  181. @Override
  182. public void copyFileBetweenBucket(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath) {
  183. try {
  184. List<String> files = listRemoteFiles(sourceBucketName, sourcePath);
  185. if (ObjectUtils.isEmpty(files)) {
  186. return;
  187. }
  188. files.stream().forEach(file -> {
  189. ossClient.copyObject(sourceBucketName, file, targetBucketName, file.replace(sourcePath, targetPath));
  190. });
  191. } catch (Exception e) {
  192. log.error("列举文件目录失败,key:" + sourcePath, e);
  193. }
  194. }
  195. @Override
  196. public void copyFilesBetweenBucket(String sourceBucketName, String targetBucketName, Map<String, String> pathMap) {
  197. if (ObjectUtils.isEmpty(pathMap)) {
  198. return;
  199. }
  200. try {
  201. for (Map.Entry<String, String> entry : pathMap.entrySet()) {
  202. copyFileBetweenBucket(sourceBucketName, entry.getKey(), targetBucketName, entry.getValue());
  203. }
  204. } catch (Exception e) {
  205. log.error(String.format("批量复制文件失败, sourceBucketName:%s, targetBucketName:%s", sourceBucketName, targetBucketName), e);
  206. }
  207. }
  208. @Override
  209. public String getFileContent(String bucketName, String remoteFilePath) {
  210. try (OSSObject ossObject = ossClient.getObject(bucketName, remoteFilePath)){
  211. InputStream objectContent = ossObject.getObjectContent();
  212. StringBuilder contentJson = new StringBuilder();
  213. try (BufferedReader reader = new BufferedReader(new InputStreamReader(objectContent))) {
  214. while (true) {
  215. String line = reader.readLine();
  216. if (line == null) break;
  217. contentJson.append(line);
  218. }
  219. } catch (IOException e) {
  220. throw e;
  221. }
  222. return contentJson.toString();
  223. } catch (Exception e) {
  224. log.error("获取文件内容失败:key:"+remoteFilePath, e);
  225. }
  226. return null;
  227. }
  228. @Override
  229. public boolean fileExist(String bucket, String objectName) {
  230. try {
  231. return ossClient.doesObjectExist(bucket, objectName);
  232. } catch (Exception e) {
  233. log.error("判断文件是否存在失败,key:"+objectName, e);
  234. }
  235. return false;
  236. }
  237. @Override
  238. public void downloadFile(String bucket, String remoteFilePath, String localPath) {
  239. try {
  240. File localFile = new File(localPath);
  241. if (!localFile.getParentFile().exists()) {
  242. localFile.getParentFile().mkdirs();
  243. }
  244. if(localFile.isDirectory()){
  245. String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/")+1);
  246. log.info("未配置文件名,使用默认文件名:{}",fileName);
  247. localPath = localPath.concat(File.separator).concat(fileName);
  248. }
  249. DownloadFileRequest request = new DownloadFileRequest(bucket, remoteFilePath);
  250. request.setDownloadFile(localPath);
  251. // 默认5个任务并发下载
  252. request.setTaskNum(5);
  253. // 启动断点续传
  254. request.setEnableCheckpoint(true);
  255. ossClient.downloadFile(request);
  256. } catch (Throwable throwable) {
  257. log.error("文件下载失败,key:"+remoteFilePath, throwable);
  258. }
  259. }
  260. @Override
  261. public URL getPresignedUrl(String bucket, String url) {
  262. java.util.Date expiration = new java.util.Date();
  263. long expTimeMillis = expiration.getTime();
  264. expTimeMillis += 1000 * 60 * 60 * 8;
  265. expiration.setTime(expTimeMillis);
  266. GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, url);
  267. generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
  268. generatePresignedUrlRequest.setExpiration(expiration);
  269. return ossClient.generatePresignedUrl(generatePresignedUrlRequest);
  270. }
  271. @Override
  272. public long getSubFileNums(String bucket, String url) {
  273. long totalSubFileNum = 0;
  274. try {
  275. boolean flag = true;
  276. String nextMaker = null;
  277. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket);
  278. //指定下一级文件
  279. listObjectsRequest.setPrefix(url);
  280. //设置分页的页容量
  281. listObjectsRequest.setMaxKeys(200);
  282. do {
  283. //获取下一页的起始点,它的下一项
  284. listObjectsRequest.setMarker(nextMaker);
  285. ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
  286. List<String> collect = objectListing.getObjectSummaries().parallelStream()
  287. .map(OSSObjectSummary::getKey).collect(Collectors.toList());
  288. if (!CollectionUtils.isEmpty(collect)) {
  289. totalSubFileNum = totalSubFileNum + collect.size();
  290. }
  291. nextMaker = objectListing.getNextMarker();
  292. //全部执行完后,为false
  293. flag = objectListing.isTruncated();
  294. } while (flag);
  295. } catch (Exception e) {
  296. log.error("获取文件数量失败,path:" + url, e);
  297. }
  298. return totalSubFileNum;
  299. }
  300. @Override
  301. public void restoreFolder(String bucket, String folderName, Integer priority) {
  302. List<String> objectList = this.listRemoteFiles(bucket, folderName);
  303. if(CollUtil.isEmpty(objectList)){
  304. return;
  305. }
  306. objectList.parallelStream().forEach(objectName -> {
  307. this.restoreFile(bucket, objectName, priority);
  308. });
  309. }
  310. @Override
  311. public void restoreFile(String bucket, String objectName, Integer priority){
  312. ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucket, objectName);
  313. // 校验Object是否为归档类型Object。
  314. StorageClass storageClass = objectMetadata.getObjectStorageClass();
  315. if (storageClass == StorageClass.ColdArchive) {
  316. // 设置解冻冷归档Object的优先级。
  317. // RestoreTier.RESTORE_TIER_EXPEDITED 表示1小时内完成解冻。
  318. // RestoreTier.RESTORE_TIER_STANDARD 表示2~5小时内完成解冻。
  319. // RestoreTier.RESTORE_TIER_BULK 表示5~12小时内完成解冻。
  320. RestoreTier restoreTier = null;
  321. switch (priority){
  322. case 1 :
  323. restoreTier = RestoreTier.RESTORE_TIER_EXPEDITED;
  324. break;
  325. case 2 :
  326. restoreTier = RestoreTier.RESTORE_TIER_STANDARD;
  327. break;
  328. default:
  329. restoreTier = RestoreTier.RESTORE_TIER_BULK;
  330. }
  331. RestoreJobParameters jobParameters = new RestoreJobParameters(restoreTier);
  332. // 配置解冻参数,以设置5小时内解冻完成,解冻状态保持2天为例。
  333. // 第一个参数表示保持解冻状态的天数,默认是1天,此参数适用于解冻Archive(归档)与ColdArchive(冷归档)类型Object。
  334. // 第二个参数jobParameters表示解冻优先级,只适用于解冻ColdArchive类型Object。
  335. RestoreConfiguration configuration = new RestoreConfiguration(1, jobParameters);
  336. //开始解冻
  337. ossClient.restoreObject(bucket, objectName, configuration);
  338. // 等待解冻完成。
  339. do {
  340. try {
  341. Thread.sleep(1000);
  342. } catch (InterruptedException e) {
  343. e.printStackTrace();
  344. }
  345. objectMetadata = ossClient.getObjectMetadata(bucket, objectName);
  346. } while (!objectMetadata.isRestoreCompleted());
  347. }
  348. }
  349. }