本文已参与「新人创作礼」活动,一起开启掘金创作之路。
接上篇文章写一下搭建完minio后怎么写一个java的测试工程,进行体验minio对象存储功能。
1.创建maven项目 导入pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>minio</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2021.0.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>LATEST</version>
</dependency>
<!-- 引入thymeleaf 做简单网页测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.22</version>
</dependency>
<!-- minio依赖-->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- 增加nacos配置 注册中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 增加nacos配置 配置中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
<build>
na <plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中 -->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.编写application.yml配置文件
server:
port: 8085
spring:
application:
name: book-minio
thymeleaf:
cache: false
servlet:
multipart:
max-file-size: 10MB
max-request-size: 100MB
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: f5caca8a-aa97-4fed-a9b3-92691006dbff
config:
server-addr: localhost:8848
namespace: f5caca8a-aa97-4fed-a9b3-92691006dbff
config:
import:
- nacos:minio-config-client-dev.yaml
management:
endpoints:
web:
exposure:
include:'*'
这块用到nacos服务注册、配置中心,如果不想用可以直接将配置写在yml文件中。
nacos中minio-config-client-dev.yaml文件的详细配置
配置了搭建的minio的地址、ip、用户名、密码、文件大小限制信息
4.工程目录
MinioController
package com.ctsi.ssdx.controller;
import com.alibaba.fastjson.JSON;
import com.ctsi.ssdx.common.Res;
import com.ctsi.ssdx.config.MinioProp;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
/**
* @Author : lizzu
* @create 2022/8/11 14:27
*/
@Slf4j
@RestController
public class MinioController {
@Autowired
private MinioClient minioClient;
@Autowired
private MinioProp minioProp;
private static final String MINIO_BUCKET = "mybucket";
@GetMapping("/list")
public List<Object> list(ModelMap map) throws Exception {
Iterable<Result<Item>> myObjects = minioClient.listObjects(MINIO_BUCKET);
Iterator<Result<Item>> iterator = myObjects.iterator();
List<Object> items = new ArrayList<>();
// String format = "{'fileName':'%s','filePath':'%s','fileSize':'%s'}";
String format = "{'fileName':'%s','fileSize':'%s'}";
while (iterator.hasNext()) {
Item item = iterator.next().get();
items.add(JSON.parse(String.format(format,
// minioProp.getEndpoint()+"/"+MINIO_BUCKET+"/"+item.objectName(),
item.objectName(), formatFileSize(item.size()))));
}
return items;
}
@PostMapping("/upload")
public Res upload(@RequestParam(name = "file", required = false) MultipartFile[] file) {
Res res = new Res();
res.setCode(500);
if (file == null || file.length == 0) {
res.setMessage("上传文件不能为空");
return res;
}
List<String> orgfileNameList = new ArrayList<>(file.length);
for (MultipartFile multipartFile : file) {
String orgfileName = multipartFile.getOriginalFilename();
orgfileNameList.add(orgfileName);
try {
InputStream in = multipartFile.getInputStream();
minioClient.putObject(MINIO_BUCKET, orgfileName, in, new PutObjectOptions(in.available(), -1));
in.close();
} catch (Exception e) {
log.error(e.getMessage());
res.setMessage("上传失败");
return res;
}
}
Map<String, Object> data = new HashMap<String, Object>();
data.put("bucketName", MINIO_BUCKET);
data.put("fileName", orgfileNameList);
res.setCode(200);
res.setMessage("上传成功");
res.setData(data);
return res;
}
@RequestMapping("/download/{fileName}")
public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {
InputStream in = null;
try {
ObjectStat stat = minioClient.statObject(MINIO_BUCKET, fileName);
response.setContentType(stat.contentType());
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
in = minioClient.getObject(MINIO_BUCKET, fileName);
IOUtils.copy(in, response.getOutputStream());
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
}
@DeleteMapping("/delete/{fileName}")
public Res delete(@PathVariable("fileName") String fileName) {
Res res = new Res();
res.setCode(200);
try {
minioClient.removeObject(MINIO_BUCKET, fileName);
} catch (Exception e) {
res.setCode(500);
log.error(e.getMessage());
}
return res;
}
private static String formatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + " B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + " KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + " MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + " GB";
}
return fileSizeString;
}
}
配置信息MinioProp
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author : lizzu
* @create 2022/8/11 14:24
*/
@Data
//@ConfigurationProperties(prefix = "minio")
@Component
public class MinioProp {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accesskey}")
private String accesskey;
@Value("${minio.secretKey}")
private String secretKey;
}
MinioConfiguration
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author : lizzu
* @create 2022/8/11 14:25
*/
@Configuration
public class MinioConfiguration {
@Autowired
private MinioProp minioProp;
@Bean
public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
MinioClient client = new MinioClient(minioProp.getEndpoint(), minioProp.getAccesskey(), minioProp.getSecretKey());
return client;
}
}
简单前端测试:
附gitee源码地址 https://gitee.com/qlglg123/minio