springboot整合minio

minio是对象存储服务。它基于Apache License 开源协议,兼容Amazon S3云存储接口。适合存储非结构化数据,如图片,音频,视频,日志等。对象文件最大可以达到5TB。

优点有高性能,可扩展,操作简单,有图形化操作界面,读写性能优异等。

minio的安装也很简单,有兴趣的可以去 https://min.io 官网看看。Mac安装详解如:

 minio服务端和客户端的安装直接用命令行安装即可。

接下来我们直接展示整合代码,首先是pom依赖文件(官网有):

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

application.yml文件:

minio:
  url: 129.0.0.1:9000 #换成自己的minio服务端地址
  access-key: minioadmin
  secret-key: minioadmin
  bucket-name: ding_server

然后是minio配置文件:

@Data
@Configuration
@Component
@PropertySource(value = {"classpath:application.yml"},
        ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties")
@ConfigurationProperties(value = "minio")
public class MinioProperties {

    @Value("${minio.url}")
    private String url;
    @Value("${minio.access-key}")
    private String accessKey;
    @Value("${minio.secret-key}")
    private String secretKey;
    @Value("${minio.bucket-name}")
    private String bucketName;

}
MinioTemplate文件:
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioTemplate {
    @Autowired
    private MinioProperties minioProperties;

    private MinioClient minioClient;

    public MinioTemplate() {}

    public MinioClient getMinioClient() {
        if (minioClient == null) {
            try {
                return new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
            } catch (InvalidEndpointException e) {
                e.printStackTrace();
            } catch (InvalidPortException e) {
                e.printStackTrace();
            }
        }
        return minioClient;
    }

    public void createBucket(String bucketName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, RegionConflictException {
        MinioClient minioClient = getMinioClient();
        if (!minioClient.bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
    }

    /**
     * 获取文件外链
     * @param bucketName bucket 名称
     * @param objectName 文件名称
     * @param expires   过期时间 <=7
     * @return
     */
    public String getObjectURL(String bucketName,String objectName,int expires) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidExpiresRangeException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        return getMinioClient().presignedGetObject(bucketName, objectName, expires);
    }

    /**
     * 获取文件
     * @param bucketName
     * @param objectName
     * @return
     */
    public InputStream getObject(String bucketName,String objectName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        return getMinioClient().getObject(bucketName, objectName);
    }

    /**
     * 上传文件
     * @param bucketName
     * @param objectName
     * @param stream
     */
    public void putObject(String bucketName, String objectName, InputStream stream) throws IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidKeyException, InvalidResponseException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidArgumentException {
        createBucket(bucketName);
        getMinioClient().putObject(bucketName,objectName,stream,stream.available(),"application/octet-stream");
    }

    public void putObject(String bucketName, String objectName, InputStream stream, int size, String contextType) throws IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidKeyException, InvalidResponseException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidArgumentException {
        createBucket(bucketName);
        getMinioClient().putObject(bucketName,objectName,stream,size,contextType);
    }

    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     */
    public void removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        getMinioClient().removeObject(bucketName,objectName);
    }

}

最后是工具类(bucketName可以外部传入,也可以写个定植,根据业务需求选择):

import com.haileer.dd.dingdingserver.config.MinioTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Service
public class MinioStorageService {

    @Autowired
    private MinioTemplate minioTemplate;

    private String bucketName = "dingding";

    /**
     * 获取文件外链
     *
     * @param objectName 文件名称
     * @param expires    过期时间 <=7
     * @return url
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#getObject
     */
    public String getObjectURL(String objectName, int expires) {
        try {
            return minioTemplate.getObjectURL(bucketName, objectName, expires);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String uploadFile(byte[] data, String filePath) {
        InputStream inputStream = new ByteArrayInputStream(data);
        String path = null;
        try {
            minioTemplate.putObject(bucketName, filePath, inputStream);
            path = filePath;
        } catch (Exception e) {

        }
        return path;
    }

    public String uploadFile(String bucketName, byte[] data, String filePath) {
        InputStream inputStream = new ByteArrayInputStream(data);
        String path = null;
        try {
            minioTemplate.putObject(bucketName, filePath, inputStream);
            path = filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    public String uploadFile(InputStream inputStream, String fileName, String contentType) {
        String path = null;
        try {
            minioTemplate.putObject(bucketName, fileName, inputStream, inputStream.available(), contentType);
            path = fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    public String uploadFile(String bucketName, InputStream inputStream, String fileName, String contentType) {
        String path = null;
        try {
            minioTemplate.putObject(bucketName, fileName, inputStream, inputStream.available(), contentType);
            path = fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    public InputStream downloadFile(String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = minioTemplate.getObject(bucketName, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public void removeFile(String filePath){
        try{
            minioTemplate.removeObject(bucketName,filePath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

我们来看看使用:

在swagger上测试:

 再去查看minio服务上:

 上传成功啦!下载图片我选择的方式是接口方式:

    @GetMapping("download")
    @ApiOperation(value = "下载文件")
    public Results download(HttpServletResponse response,@RequestParam("filePath")String filePath)  {
        if(!StringUtils.isEmpty(filePath)){
            InputStream inputStream = minioStorageService.downloadFile(filePath);
            if (inputStream != null) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
                response.setCharacterEncoding("UTF-8");
                byte[] buffer = new byte[1024];
                BufferedInputStream bis = null;
                try {
                    bis = new BufferedInputStream(inputStream);
                    ServletOutputStream outputStream = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        outputStream.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
        return new Results(500, "下载失败");
    }

然后用访问接口的方式下载图片就可以了!http://127.0.0.1:8080/file/download?filePath= 即可。

以上就是springboot整合minio服务存储对象以及上传下载文件的全部代码啦。下次见!

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值