SpringBoot集成Minio

avatar
作者
猴君
阅读量:0
public class MinIOConfig {     @Autowired     private MinIOConfigProperties minIOConfigProperties;      @Bean     public MinioClient buildMinioClient() {         return MinioClient                 .builder()                 .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())                 .endpoint(minIOConfigProperties.getEndpoint())                 .build();     } }
@Data @ConfigurationProperties(prefix = "minio") @Component public class MinIOConfigProperties implements Serializable {      private String accessKey;     private String secretKey;     private String bucket;     private String endpoint;     private String readPath;  }
public interface MinioFileService {      /**      * 下载文件      * @param pathUrl      * @param response      */     void downLoadFile(String pathUrl, HttpServletResponse response) ;      /**      * 上传文件到指定tong桶下面的指定目录      * @param bucketName   桶名称      * @param folderPath   目录名称      * @param file         文件      */     String downLoadFileByPath(String bucketName,String folderPath, MultipartFile file) throws Exception;       /**      * 上传文件      * @param file      * @return      * @throws Exception      */      String uploadFile(File file) throws Exception;       /**      * 创建临时目录      * @return      */     File createTempDir();       /**      * 删除文件      * @param pathUrl      */      void delete(String pathUrl) ;      /**      * 列出所有bucket名称      * @return      * @throws Exception      */      List<String> listBucketNames() throws Exception;      /**      * 创建bucket      * @param bucketName      * @return      * @throws Exception      */      boolean makeBucket(String bucketName) throws Exception;      /**      * 删除bucket      * @param bucketName      * @return      * @throws Exception      */      boolean removeBucket(String bucketName) throws Exception;      /**      * 列出bucket的所有对象名称      * @param bucketName      * @return      * @throws Exception      */      List<String> listObjectNames(String bucketName) throws Exception;        Iterable<Result<Item>> listObjects(String bucketName) throws Exception; } 
@Slf4j @Import(MinIOConfig.class) @Service public class MinioFileServiceImpl  implements MinioFileService {       @Autowired     private MinioClient minioClient;      @Autowired     private MinIOConfigProperties minIOConfigProperties;      private final static String separator = "/";      @Value("${Temporary_file_address}")     private String Temporary_file_address;      /**      * 下载文件      *      * @param pathUrl 文件全路径      * @return 文件流      */     @Override     public  void downLoadFile(String pathUrl, HttpServletResponse response) {         String[] pathItems = pathUrl.split("/");         String originFileName = pathItems[pathItems.length - 1];         String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");         int index = key.indexOf(separator);         //String bucket = key.substring(0,index);         String filePath = key.substring(index + 1);         InputStream inputStream = null;         try {             inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());             response.setHeader("Content-Disposition", "attachment;filename=" + originFileName);             response.setContentType("application/force-download");             response.setCharacterEncoding("UTF-8");             IOUtils.copy(inputStream, response.getOutputStream());             System.out.println("下载成功");         } catch (Exception e) {             log.error("minio down file error.  pathUrl:{}", pathUrl);             e.printStackTrace();         } finally {             try {                 inputStream.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     }      @Override     public String downLoadFileByPath(String bucketName, String folderPath, MultipartFile file)  throws Exception{         String endpoint = minIOConfigProperties.getEndpoint();         // 上传文件到指定文件夹         String objectName = folderPath+"/" + file.getOriginalFilename();         PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)                 .bucket(bucketName)                 .contentType(file.getContentType())                 .stream(file.getInputStream(), file.getSize(), -1).build();         minioClient.putObject(objectArgs);         return endpoint + "/" + bucketName + "/" + objectName;      }      //    @Override //    public String uploadFile(MultipartFile file) throws Exception { //        String bucketName = minIOConfigProperties.getBucket(); //        String endpoint = minIOConfigProperties.getEndpoint(); //        InputStream inputStream = file.getInputStream(); //        // 检查存储桶是否已经存在 //        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); //        if (isExist) { //            System.out.println("Bucket already exists."); //        } else { //            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); //        } //        String originalFilename = file.getOriginalFilename(); //        //拼接生成新的UUID形式的文件名 //        String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + //                UUID.randomUUID().toString().replaceAll("-", "") //                + originalFilename.substring(originalFilename.lastIndexOf(".")); // //        PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName) //                .bucket(bucketName) //                .contentType(file.getContentType()) //                .stream(inputStream, file.getSize(), -1).build(); //        minioClient.putObject(objectArgs); //        inputStream.close(); //        //组装桶中文件的访问url //        String resUrl = endpoint + "/" + bucketName + "/" + objectName; //        return resUrl; //    }     @Override     public String uploadFile(File file) throws Exception {         String bucketName = minIOConfigProperties.getBucket();         String endpoint = minIOConfigProperties.getEndpoint();          try {             // 检查存储桶是否已经存在             if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {                 minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());             }             // 拼接生成新的UUID形式的文件名             String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) +                     UUID.randomUUID().toString().replaceAll("-", "") +                     file.getName().substring(file.getName().lastIndexOf("."));             // 上传             minioClient.uploadObject(UploadObjectArgs.builder()                     .bucket(bucketName)                     .object(objectName)                     .filename(file.getAbsolutePath())                     .build());             // 组装桶中文件的访问url             return endpoint + "/" + bucketName + "/" + objectName;         } catch (Exception e) {             log.error("上传文件 {} 失败: {}", file.getName(), e.getMessage());             e.printStackTrace();             throw new ServiceException(1000000500, "上传文件失败:" + e);         } finally {             // 删除临时文件             this.deleteTempFile(file);         }     }      /**      * 在应用启动时      * 创建临时目录      */     @Override     public File createTempDir() {         String property = System.getProperty("user.home");         // 生成或指定文件存储的目录         File dir = new File(property);         if (!dir.exists()) {             dir.mkdirs();         }         return dir;     }     /**      * 删除临时文件      * @param file file      */     private void deleteTempFile(File file) {         try {             Files.deleteIfExists(Paths.get(file.getAbsolutePath()));         } catch (IOException e) {             log.error("删除临时文件失败: {}", file.getAbsolutePath(), e);         }     }       /**      * 删除文件      *      * @param pathUrl 文件全路径      */     @Override     public void delete(String pathUrl) {         String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");         int index = key.indexOf(separator);         String bucket = key.substring(0, index);         String filePath = key.substring(index + 1);         // 删除Objects         RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();         try {             minioClient.removeObject(removeObjectArgs);         } catch (Exception e) {             log.error("minio remove file error.  pathUrl:{}", pathUrl);             e.printStackTrace();         }     }      public List<Bucket> listBuckets()             throws Exception {         return minioClient.listBuckets();     }      public boolean bucketExists(String bucketName) throws Exception {         boolean flag = minioClient.bucketExists( BucketExistsArgs.builder().bucket(bucketName).build());         if (flag) {             return true;         }         return false;     }      @Override     public List<String> listBucketNames() throws Exception{         List<Bucket> bucketList = listBuckets();         List<String> bucketListName = new ArrayList<>();         for (Bucket bucket : bucketList) {             bucketListName.add(bucket.name());         }         return bucketListName;     }      @Override     public boolean makeBucket(String bucketName) throws Exception{         boolean flag = this.bucketExists(bucketName);         if (!flag) {             minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());             return true;         } else {             return false;         }     }      @Override     public boolean removeBucket(String bucketName) throws Exception{         boolean flag = bucketExists(bucketName);         if (flag) {             Iterable<Result<Item>> myObjects = listObjects(bucketName);             for (Result<Item> result : myObjects) {                 Item item = result.get();                 // 有对象文件,则删除失败                 if (item.size() > 0) {                     return false;                 }             }             // 删除存储桶,注意,只有存储桶为空时才能删除成功。             minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());             flag = bucketExists(bucketName);             if (!flag) {                 return true;             }         }         return false;     }     @Override     public List<String> listObjectNames(String bucketName) throws Exception{         List<String> listObjectNames = new ArrayList<>();         boolean flag = bucketExists(bucketName);         if (flag) {             Iterable<Result<Item>> myObjects = listObjects(bucketName);             for (Result<Item> result : myObjects) {                 Item item = result.get();                 listObjectNames.add(item.objectName());             }         }         return listObjectNames;     }      public Iterable<Result<Item>> listObjects(String bucketName) throws Exception {         boolean flag = bucketExists(bucketName);         if (flag) {             return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());         }         return null;     }  } 
public class MultipartConfigElement {     @Bean     public javax.servlet.MultipartConfigElement multipartConfigElement() {         MultipartConfigFactory factory = new MultipartConfigFactory();         factory.setLocation("/home/temp");         return factory.createMultipartConfig();     }   }

添加依赖:

 <dependency>             <groupId>io.minio</groupId>             <artifactId>minio</artifactId>             <version>7.1.0</version>  </dependency>

配置application.yam文件:

//application.yam文件 minio:   accesskey: xxxxxxxxxxxxxxxxxxxxxxx   secretKey: xxxxxxxxxxxxxxxxxxxxx   endpoint: http://xxxxxxxx:端口号   readPath: http://xxxxxxxx:端口号 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!