SpringBoot 使用minio 分布式文件服务

SpringBoot 使用minio 分布式文件服务
依赖
<!--minio文件系统-->
<dependency>
	<groupId>io.minio</groupId>
	<artifactId>minio</artifactId>
	<version>6.0.2</version>
</dependency>
<!--Lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>
1、在application.yml中配置
# 文件系统
minio:
  url: http://127.0.0.1:9000
  access-key: xxxxxxxxx
  secret-key: xxxxxxxx
  bucket-name: zdrjy
2、注入配置到properties
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
   /**
    * minio 服务地址 http://ip:port
    */
   private String url;
   /**
    * 用户名
    */
   private String accessKey;
   /**
    * 密码
    */
   private String secretKey;
    /**
    * 桶名称
    */
   private String bucketName;
}
3、初始化 MinioClient 自动注入到 spring 容器
@AllArgsConstructor
@EnableConfigurationProperties({MinioProperties.class})
public class MinioAutoConfiguration {
   private final MinioProperties properties;

   @Bean
   @ConditionalOnMissingBean(MinioTemplate.class)
   @ConditionalOnProperty(name = "minio.url")
   MinioClient minioClient() {
      return new MinioClient(
            properties.getUrl(),
            properties.getAccessKey(),
            properties.getSecretKey()
      );
   }
}
4、创建Service
@Slf4j
@Component
@AllArgsConstructor
public class MinioStorageService {
    
    private final MinioClient minioClient;
    private final MinioProperties minioProperties;
    
    /**
    * 上传文件
    */
    public String uploadFile(byte[] data, String filePath) {
        InputStream inputStream = new ByteArrayInputStream(data);
        String path;
        try {
            client.putObject(minioClient.getBucketName(), filePath, inputStream, inputStream.available(), getContextType(fileName));
            path = filePath;
        } catch (Exception e) {
            log.error("=====minio:"+e.getMessage());
        }
        return path;
    }
    
        
    /**
    * 删除文件
    */
   public boolean delete(String filePath) {
        try {
            client.removeObject(minioClient.getBucketName(),filePath);
            return true;
        } catch (Exception e) {
            log.error("====minio:删除失败,"+e.getMessage());
        }
       	return false;
    }
    
    public String getContextType(String path){
        String suffix = path.substring(path.lastIndexOf(".") + 1 );
        String type = "application/octet-stream";
        if(suffix.equals("jpg")||suffix.equals("jpeg")||suffix.equals("png")||suffix.equals("bmp")||suffix.equals("gif")){
            type = "image/jpeg";
        }
        return type;
    }
    
}
5、最后 Controller
@RestController
@RequestMapping("oss")
@AllArgsConstructor
public class OssController {
    
    private final MinioStorageService minioStorageService;
    
    /**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		//上传文件
        String path = "/psm_memory_service/picture/fore-end/"+file.getOriginalFilename();
		String url = minioStorageService.uploadFile(file.getBytes(),path);
		return R.ok().put("url", url);
    }
    
    /**
	 * 删除
	 */
	@RequestMapping("/delete/{id}")
	public R delete(@PathVariable("id") String id){
		SysOss oss = sysOssService.getById(id);
		ossFactory.build().delete(oss.getUrl());
		sysOssService.removeById(id);
		return R.ok();
	}
    
}

具体CURD源码可以看 https://github.com/yzcheng90/X-SpringBoot

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
在Spring Boot使用MinIO可以通过以下几个步骤: 1. 引入MinIO的依赖:在`pom.xml`文件添加MinIO的依赖。 ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>RELEASE.2021-03-03T02-57-17Z</version> </dependency> ``` 2. 配置MinIO连接信息:在`application.properties`或`application.yml`文件添加MinIO的连接信息。 ```properties # MinIO服务器的连接地址 minio.endpoint=http://localhost:9000 # MinIO服务器的访问密钥 minio.accessKey=minio-access-key # MinIO服务器的访问密钥 minio.secretKey=minio-secret-key ``` ```yaml minio: endpoint: http://localhost:9000 accessKey: minio-access-key secretKey: minio-secret-key ``` 3. 创建MinIO客户端:在Spring Boot的配置类创建MinIO客户端的Bean。 ```java import io.minio.MinioClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MinioConfig { @Value("${minio.endpoint}") private String endpoint; @Value("${minio.accessKey}") private String accessKey; @Value("${minio.secretKey}") private String secretKey; @Bean public MinioClient minioClient() { return MinioClient.builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); } } ``` 4. 使用MinIO进行文件上传和下载:在需要使用MinIO的地方注入MinIO客户端,然后使用MinIO客户端的方法进行文件上传和下载操作。 ```java import io.minio.MinioClient; import io.minio.UploadObjectArgs; import io.minio.GetObjectArgs; @Service public class MinioService { private final MinioClient minioClient; public MinioService(MinioClient minioClient) { this.minioClient = minioClient; } public void uploadFile(String bucketName, String objectName, InputStream inputStream, long size, String contentType) throws Exception { minioClient.uploadObject( UploadObjectArgs.builder() .bucket(bucketName) .object(objectName) .stream(inputStream, size, -1) .contentType(contentType) .build()); } public InputStream downloadFile(String bucketName, String objectName) throws Exception { return minioClient.getObject( GetObjectArgs.builder() .bucket(bucketName) .object(objectName) .build()); } // 其他操作... } ``` 这样就可以在Spring Boot使用MinIO进行文件的上传和下载了。你可以根据具体的需求,进一步扩展MinIO的功能,例如创建、删除、列举存储桶等操作。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值