minio 配置
1:下载 minio.exe
2:安装启动
把下载好的minio.exe 放到你喜欢的文件夹下
进入cmd minio.exe 所在目录 输入 以下指令
.\minio.exe server d:\minio\data
红框是你的登录账号 和 登录密码 也就是你的 ACCESS-KEY 和 SECRET-KEY
打开游览器 输入 http://127.0.0.1:9000/ 进入登录界面
创建空间名 也就是 桶
要注意给空间分配读写权限
修改登录账号和密码 ACCESS-KEY 和 SECRET-KEY
打开config.json 文件
查找 access_key 和 secret_key 更改成 你自己的 数据 点击保存 重启 生效
下面配置minio 服务 随着系统的启动自启动
winsw下载配置:
- 地址:https://github.com/winsw/winsw/releases
- 将WinSW.exe复制到自定义的目录,并重命名为自己想命名的服务名称minio-server.exe
- 同目录下创建minio-server.xml。特别注意,xml和exe必须同名
- 配置minio-server.xml文件
- 使用minio-server.exe install安装服务
- 安装完后,去服务中启动服务。启动成功就可以正常使用minio啦
- 使用minio-server.exe uninstall卸载服务
具体配置:
<service>
<id>minio-server</id>
<name>minio-server</name>
<description>minio文件存储服务器</description>
<!-- 可设置环境变量 -->
<env name="HOME" value="%BASE%"/>
<executable>%BASE%\minio.exe</executable>
<arguments>server "%BASE%\data"</arguments>
<!-- <logmode>rotate</logmode> -->
<logpath>%BASE%\logs</logpath>
<log mode="roll-by-size-time">
<sizeThreshold>10240</sizeThreshold>
<pattern>yyyyMMdd</pattern>
<autoRollAtTime>00:00:00</autoRollAtTime>
<zipOlderThanNumDays>5</zipOlderThanNumDays>
<zipDateFormat>yyyyMMdd</zipDateFormat>
</log>
</service>
目录结构:
服务:
minio配置就结束了
整合springboot
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
application.yml 配置
minio:
endpoint: 127.0.0.1 #ip地址 是一个URL,域名,IPv4或者IPv6地址
port: 9000 #端口号
accessKey: XXXXX #用于唯一标识你的账户
secretKey: XXXXXXXXXXXXXXX #你账户的密码
secure: false #如果是true,则用的是https而不是http,默认值是true
bucketName: "house-keep" #默认存储桶 空间名称 - 桶名称
configDir: "/home/data/" #配置目录
application.yml 文件读取工具类
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
/**写一个SpringBoot读取Yaml配置文件的类
* @author WangDong
* @description 创建时间:
*/
public class BootYml {
/**
* 环境配置路径的键值
*/
private String active;
/**
* 引入yml的键值
*/
private String include;
/**
* 配置文件的前缀
*/
private String prefix;
/**
* <p>方法名称:根据application.yml转化为LinkedHashMap.</p>
* <p>详细描述:会解析spring.profiles.active启用的配置和spring.profiles.include引入的文件.</p>
* <p>创建时间:2019-07-10 17:39:38</p>
* @param path application.yml
* @return the linked hash map
* @author "lixingwu"
*/
public LinkedHashMap loadAs(String path) {
// 组合一个map,把启用的配置,引入的文件组合起来
LinkedHashMap<String, Object> mapAll = new LinkedHashMap<>();
LinkedHashMap<String, Object> mainMap = yml2Map(path);
// 读取启用的配置
Object active = mainMap.get(this.active);
if (null != active) {
mapAll.putAll(yml2Map(StrUtil.format("{}-{}.yml", this.prefix, active)));
}
// 加载引入的yml
Object include = mainMap.get(this.include);
// include是使用逗号分隔开的,需要切割一下
List<String> split = StrSpliter.split(Convert.toStr(include), StrUtil.C_COMMA, true, true);
for (String inc : split) {
mapAll.putAll(yml2Map(StrUtil.format("{}-{}.yml", this.prefix, inc)));
}
// 主配置覆盖其他配置
mapAll.putAll(mainMap);
// 把map转化为字符串
//String mapString = MapUtil.joinIgnoreNull(mapAll, "\n", "=");
// 再把map字符串转化为yamlStr字符串
//String yamlStr = properties2YamlStr(mapString);
// 使用Yaml构建LinkedHashMap
//return JSON.parseObject(mapString,LinkedHashMap.class, Feature.OrderedField);
return mapAll;
}
/**
* <p>方法名称:Yml 格式转 LinkedHashMap.</p>
* <p>详细描述:转载自 https://www.cnblogs.com/xujingyang/p/10613206.html .</p>
* <p>创建时间:2019-07-10 09:30:19</p>
* <p>创建作者:李兴武</p>
* <p>修改记录:</p>
*
* @param path Yml路径
* @author "lixingwu"
*/
public LinkedHashMap<String, Object> yml2Map(String path) {
final String dot = ".";
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
ClassPathResource resource = new ClassPathResource(path);
// 文件不存在,置空
if (null == resource) {
return map;
}
BufferedReader reader = resource.getReader(Charset.defaultCharset());
try {
YAMLFactory yamlFactory = new YAMLFactory();
YAMLParser parser = yamlFactory.createParser(reader);
StringBuilder key = new StringBuilder();
String value;
JsonToken token = parser.nextToken();
while (token != null) {
if (!JsonToken.START_OBJECT.equals(token)) {
if (JsonToken.FIELD_NAME.equals(token)) {
if (key.length() > 0) {
key.append(dot);
}
key.append(parser.getCurrentName());
token = parser.nextToken();
if (JsonToken.START_OBJECT.equals(token)) {
continue;
}
value = parser.getText();
map.put(key.toString(), value);
int dotOffset = key.lastIndexOf(dot);
if (dotOffset > 0) {
key = new StringBuilder(key.substring(0, dotOffset));
}
} else if (JsonToken.END_OBJECT.equals(token)) {
int dotOffset = key.lastIndexOf(dot);
if (dotOffset > 0) {
key = new StringBuilder(key.substring(0, dotOffset));
} else {
key = new StringBuilder();
}
}
}
token = parser.nextToken();
}
parser.close();
return map;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <p>方法名称:Properties内容转化为yaml内容.</p>
* <p>详细描述:.</p>
* <p>创建时间:2019-07-10 15:06:48</p>
* <p>创建作者:李兴武</p>
* <p>修改记录:</p>
*
* @param content Properties内容
* @return the string
* @author "lixingwu"
*/
public String properties2YamlStr(String content) {
// 临时生成yml
String filePath = FileUtil.getTmpDirPath() + "/temp.yml";
JsonParser parser;
JavaPropsFactory factory = new JavaPropsFactory();
try {
parser = factory.createParser(content);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
YAMLFactory yamlFactory = new YAMLFactory();
YAMLGenerator generator = yamlFactory.createGenerator(FileUtil.getOutputStream(filePath));
JsonToken token = parser.nextToken();
while (token != null) {
if (JsonToken.START_OBJECT.equals(token)) {
generator.writeStartObject();
} else if (JsonToken.FIELD_NAME.equals(token)) {
generator.writeFieldName(parser.getCurrentName());
} else if (JsonToken.VALUE_STRING.equals(token)) {
generator.writeString(parser.getText());
} else if (JsonToken.END_OBJECT.equals(token)) {
generator.writeEndObject();
}
token = parser.nextToken();
}
parser.close();
generator.flush();
generator.close();
// 读取临时生成yml的内容
String ymlContent = FileUtil.readUtf8String(filePath);
// 删除临时生成yml
FileUtil.del(filePath);
return ymlContent;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getInclude() {
return include;
}
public void setInclude(String include) {
this.include = include;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* 获取yml 属性值
*/
public static LinkedHashMap ymlProp(String yml) {
BootYml yaml = new BootYml();
yaml.setActive("spring.profiles.active");
yaml.setInclude("spring.profiles.include");
yaml.setPrefix("application");
return yaml.loadAs(yml);
}
MinioConfig
import com.xz.boot.common.generator.BootYml;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
@Data
@Component
public class MinioConfig {
private static LinkedHashMap prop = BootYml.ymlProp("application.yml");
private String endpoint = prop.get("minio.endpoint").toString();
private Integer port = Integer.valueOf(prop.get("minio.port").toString());
private String accessKey = prop.get("minio.accessKey").toString();
private String secretKey = prop.get("minio.secretKey").toString();
private Boolean secure = Boolean.getBoolean(prop.get("minio.secure").toString());
public static String bucketName = prop.get("minio.bucketName").toString();
public String configDir = prop.get("minio.configDir").toString();
@Bean
public MinioClient getMinioClient() throws InvalidEndpointException, InvalidPortException {
MinioClient minioClient = new MinioClient(endpoint, port, accessKey, secretKey,secure);
return minioClient;
}
MinioUtils
import com.xz.boot.common.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.ErrorResponseException;
import io.minio.errors.InvalidExpiresRangeException;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Component
public class MinioUtils {
@Autowired
private MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
/**
* 检查存储桶是否存在
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean bucketExists(String bucketName) {
boolean flag = minioClient.bucketExists(bucketName);
if (flag) {
return true;
}
return false;
}
/**
* 创建存储桶
*
* @param bucketName 存储桶名称
*/
@SneakyThrows
public boolean makeBucket(String bucketName) {
boolean flag = bucketExists(bucketName);
if (!flag) {
minioClient.makeBucket(bucketName);
return true;
} else {
return false;
}
}
/**
* 列出所有存储桶名称
*
* @return
*/
@SneakyThrows
public List<String> listBucketNames() {
List<Bucket> bucketList = listBuckets();
List<String> bucketListName = new ArrayList<>();
for (Bucket bucket : bucketList) {
bucketListName.add(bucket.name());
}
return bucketListName;
}
/**
* 列出所有存储桶
*
* @return
*/
@SneakyThrows
public List<Bucket> listBuckets() {
return minioClient.listBuckets();
}
/**
* 删除存储桶
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean removeBucket(String bucketName) {
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(bucketName);
flag = bucketExists(bucketName);
if (!flag) {
return true;
}
}
return false;
}
/**
* 列出存储桶中的所有对象名称
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public List<String> listObjectNames(String bucketName) {
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;
}
/**
* 列出存储桶中的所有对象
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public Iterable<Result<Item>> listObjects(String bucketName) {
boolean flag = bucketExists(bucketName);
if (flag) {
return minioClient.listObjects(bucketName);
}
return null;
}
/**
* 通过文件上传到对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, String fileName) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(bucketName, objectName, fileName, null);
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 文件上传
* @param bucketName
* @param multipartFile
* @param filename
* @return url
*/
@SneakyThrows
public String putObject(String bucketName, MultipartFile multipartFile, String filename) {
PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
putObjectOptions.setContentType(multipartFile.getContentType());
makeBucket(bucketName);
minioClient.putObject(bucketName, filename, multipartFile.getInputStream(), putObjectOptions);
return filename;
//return getObjectUrl(MinioConfig.bucketName, filename);
}
/**
* 通过InputStream上传对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param stream 要上传的流
* @return
*/
@SneakyThrows
public boolean putObject(String bucketName, String objectName, InputStream stream) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 以流的形式获取一个文件对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(bucketName, objectName);
return stream;
}
}
return null;
}
/**
* 以流的形式获取一个文件对象(断点下载)
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param offset 起始字节的位置
* @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
InputStream stream = minioClient.getObject(bucketName, objectName, offset, length);
return stream;
}
}
return null;
}
/**
* 下载并将文件保存到本地
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param fileName File name
* @return
*/
@SneakyThrows
public boolean getObject(String bucketName, String objectName, String fileName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = statObject(bucketName, objectName);
if (statObject != null && statObject.length() > 0) {
minioClient.getObject(bucketName, objectName, fileName);
return true;
}
}
return false;
}
/**
* 删除一个对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
*/
@SneakyThrows
public boolean removeObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(StringUtils.isBlank(bucketName)?MinioConfig.bucketName:bucketName, objectName);
return true;
}
return false;
}
/**
* 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
*
* @param bucketName 存储桶名称
* @param objectNames 含有要删除的多个object名称的迭代器对象
* @return
*/
@SneakyThrows
public List<String> removeObject(String bucketName, List<String> objectNames) {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}
/**
* 生成一个给HTTP GET请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
@SneakyThrows
public String presignedGetObject(String bucketName, String objectName, Integer expires) {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
throw new InvalidExpiresRangeException(expires,
"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
}
url = minioClient.presignedGetObject(bucketName, objectName, expires);
}
return url;
}
/**
* 生成一个给HTTP PUT请求用的presigned URL。
* 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
* @return
*/
@SneakyThrows
public String presignedPutObject(String bucketName, String objectName, Integer expires) {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
throw new InvalidExpiresRangeException(expires,
"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
}
url = minioClient.presignedPutObject(bucketName, objectName, expires);
}
return url;
}
/**
* 获取对象的元数据
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public ObjectStat statObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = minioClient.statObject(bucketName, objectName);
return statObject;
}
return null;
}
/**
* 文件访问路径
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public String getObjectUrl(String bucketName, String objectName) {
// boolean flag = bucketExists(bucketName);
// String url = "";
// if (flag) {
// url = minioClient.getObjectUrl(bucketName, objectName);
// }
// return url;
return minioClient.getObjectUrl(StringUtils.isBlank(bucketName)?MinioConfig.bucketName:bucketName, objectName);
}
public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
try {
InputStream file = minioClient.getObject(bucketName, fileName);
String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
if (StringUtils.isNotBlank(originalName)) {
filename = originalName;
}
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
ServletOutputStream servletOutputStream = response.getOutputStream();
int len;
byte[] buffer = new byte[1024];
while ((len = file.read(buffer)) > 0) {
servletOutputStream.write(buffer, 0, len);
}
servletOutputStream.flush();
file.close();
servletOutputStream.close();
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
调用示例
@ResponseBody
@PostMapping(value = "/min/save")
@ApiOperation("上传本地minio文件存储服务器")
public ResultModel min(@RequestParam("file") MultipartFile file) {
if (null == file) {
return ResultModel.error("请选择文件再上传");
}
String filename = file.getOriginalFilename();
String suffix = filename.substring(filename.lastIndexOf("."));
String name = StringUtil.orderNo(6) + suffix;
String src = minioUtil.putObject(MinioConfig.bucketName, file, name);
String url = minioUtil.getObjectUrl(MinioConfig.bucketName, src);
JSONObject object = new JSONObject();
object.put("src", url);
object.put("id", src);
object.put("name", filename);
return ResultModel.success(object);
}
@ResponseBody
@PostMapping(value = "/min/delete")
@ApiOperation("删除本地minio文件")
public ResultModel minDelete(String id) {
boolean b = minioUtil.removeObject(MinioConfig.bucketName, id);
if (b) {
return ResultModel.success("删除文件成功!");
}
return ResultModel.error("删除文件失败!");
}
完结 !!! 整理不易,看到麻烦点个赞再走呀 !!!