springboot整合minio
创始人
2024-03-02 03:39:18
0

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

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

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

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

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

io.miniominio8.4.3

application.yml文件:

minio:url: 129.0.0.1:9000 #换成自己的minio服务端地址access-key: minioadminsecret-key: minioadminbucket-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 {@Autowiredprivate 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 {@Autowiredprivate 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服务存储对象以及上传下载文件的全部代码啦。下次见!

相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
群晖外网访问终极解决方法:IP... 写在前面的话 受够了群晖的quickconnet的小水管了,急需一个新的解决方法&#x...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
Azure构建流程(Power... 这可能是由于配置错误导致的问题。请检查构建流程任务中的“发布构建制品”步骤,确保正确配置了“Arti...