minio安装与java sdk

1.minio安装

minio安装地址

mac安装

# 安装
brew install minio/stable/minio
# 启动
minio server /etc/default/minio --console-address ":9001"
#/etc/default/minio 文件存放目录
#9001 web访问端口
#启动完成
WARNING: Detected default credentials 'minioadmin:minioadmin', we recommend that you change these values with 'MINIO_ROOT_USER' and 'MINIO_ROOT_PASSWORD' environment variables
MinIO Object Storage Server
Copyright: 2015-2023 MinIO, Inc.
License: GNU AGPLv3 <https://www.gnu.org/licenses/agpl-3.0.html>
Version: RELEASE.2023-02-27T18-10-45Z (go1.19.6 darwin/arm64)

Status:         1 Online, 0 Offline. 
API: http://192.168.40.49:9000  http://192.168.40.41:9000  http://127.0.0.1:9000                       
RootUser: minioadmin 
RootPass: minioadmin 
Console: http://192.168.40.49:9001 http://192.168.40.41:9001 http://127.0.0.1:9001            
RootUser: minioadmin 
RootPass: minioadmin 

Command-line: https://min.io/docs/minio/linux/reference/minio-mc.html#quickstart
   $ mc alias set myminio http://192.168.40.49:9000 minioadmin minioadmin

Documentation: https://min.io/docs/minio/linux/index.html
Warning: The standard parity is set to 0. This can lead to data loss.

window安装

# 安装
https://dl.min.io/server/minio/release/windows-amd64/minio.exe
# 启动 C:\minio替换为存储目录
.\minio.exe server C:\minio --console-address :9001

启动界面

账号密码都在启动时打印

创建密钥(客户端链接用)
minio安装与java sdk_第1张图片

2. springboot集成

  • 导包
<dependency>
			<groupId>io.minio</groupId>
			<artifactId>minio</artifactId>
			<version>8.4.3</version>
		</dependency>
		<dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp</artifactId>
			<version>4.10.0</version>
		</dependency>

官方示例
github代码示例

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class FileUploader {
  public static void main(String[] args)
      throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    try {
      // Create a minioClient with the MinIO server playground, its access key and secret key.
      MinioClient minioClient =
          MinioClient.builder()
              .endpoint("https://play.min.io")
              .credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
              .build();

      // Make 'asiatrip' bucket if not exist.
      boolean found =
          minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
      if (!found) {
        // Make a new bucket called 'asiatrip'.
        minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
      } else {
        System.out.println("Bucket 'asiatrip' already exists.");
      }

      // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
      // 'asiatrip'.
      minioClient.uploadObject(
          UploadObjectArgs.builder()
              .bucket("asiatrip")
              .object("asiaphotos-2015.zip")
              .filename("/home/user/Photos/asiaphotos.zip")
              .build());
      System.out.println(
          "'/home/user/Photos/asiaphotos.zip' is successfully uploaded as "
              + "object 'asiaphotos-2015.zip' to bucket 'asiatrip'.");
    } catch (MinioException e) {
      System.out.println("Error occurred: " + e);
      System.out.println("HTTP trace: " + e.httpTrace());
    }
  }
}

JavaAPI详细文档

  • 贴一个我自己的例子
String minioBucketName = "test";
 BufferedInputStream inputStream = FileUtil.getInputStream("/Users/zs/Desktop/1.jpeg");
        MinioClient client = MinioClient.builder()
                .endpoint("http://127.0.0.1:9000")// 通信端口是9000
                .credentials("1VfcS0Tl3zmWz1iA", // 上面生成的accessKey
                "nCNtTIst0QpJxbshzPx4mRDlNGxijaRC")// 上面生成的secretKey
                .build();
                 // bucket是否存在
            boolean found = client.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(minioBucketName).build());
            // 不存在则创建
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioBucketName).build());
            }
        ObjectWriteResponse test = client.putObject(PutObjectArgs.builder()
                .bucket(minioBucketName)
                .object("1.jpeg")
                .stream(inputStream, inputStream.available(), -1)
                // String contentType = MimeTypeEnum.getByExtension("jpeg")..getMimeType();
                .contentType("image/jpeg")// 这个有点坑必须写对,不然报错,不写默认流上传,无法看
                .build());
// 文件访问地址:http://127.0.0.1:9000/bucket/文件名
  • 根据后缀返回对应的contentType
import org.apache.commons.lang.StringUtils;
import lombok.Getter;

/**
 * 依据文件后缀名返回ContentType
 * @author zzg
 *
 */
@Getter
public enum MimeTypeEnum {

    AAC("acc", "AAC音频", "audio/aac"),

    ABW("abw", "AbiWord文件", "application/x-abiword"),

    ARC("arc", "存档文件", "application/x-freearc"),

    AVI("avi", "音频视频交错格式", "video/x-msvideo"),

    AZW("azw", "亚马逊Kindle电子书格式", "application/vnd.amazon.ebook"),

    BIN("bin", "任何类型的二进制数据", "application/octet-stream"),

    BMP("bmp", "Windows OS / 2位图图形", "image/bmp"),

    BZ("bz", "BZip存档", "application/x-bzip"),

    BZ2("bz2", "BZip2存档", "application/x-bzip2"),

    CSH("csh", "C-Shell脚本", "application/x-csh"),

    CSS("css", "级联样式表(CSS)", "text/css"),

    CSV("csv", "逗号分隔值(CSV)", "text/csv"),

    DOC("doc", "微软Word文件", "application/msword"),

    DOCX("docx", "Microsoft Word(OpenXML)", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),

    EOT("eot", "MS Embedded OpenType字体", "application/vnd.ms-fontobject"),

    EPUB("epub", "电子出版物(EPUB)", "application/epub+zip"),

    GZ("gz", "GZip压缩档案", "application/gzip"),

    GIF("gif", "图形交换格式(GIF)", "image/gif"),

    HTM("htm", "超文本标记语言(HTML)", "text/html"),

    HTML("html", "超文本标记语言(HTML)", "text/html"),

    ICO("ico", "图标格式", "image/vnd.microsoft.icon"),

    ICS("ics", "iCalendar格式", "text/calendar"),

    JAR("jar", "Java存档", "application/java-archive"),

    JPEG("jpeg", "JPEG图像", "image/jpeg"),

    JPG("jpg", "JPEG图像", "image/jpeg"),

    JS("js", "JavaScript", "text/javascript"),

    JSON("json", "JSON格式", "application/json"),

    JSONLD("jsonld", "JSON-LD格式", "application/ld+json"),

    MID("mid", "乐器数字接口(MIDI)", "audio/midi"),

    MIDI("midi", "乐器数字接口(MIDI)", "audio/midi"),

    MJS("mjs", "JavaScript模块", "text/javascript"),

    MP3("mp3", "MP3音频", "audio/mpeg"),

    MPEG("mpeg", "MPEG视频", "video/mpeg"),

    MPKG("mpkg", "苹果安装程序包", "application/vnd.apple.installer+xml"),

    ODP("odp", "OpenDocument演示文稿文档", "application/vnd.oasis.opendocument.presentation"),

    ODS("ods", "OpenDocument电子表格文档", "application/vnd.oasis.opendocument.spreadsheet"),

    ODT("odt", "OpenDocument文字文件", "application/vnd.oasis.opendocument.text"),

    OGA("oga", "OGG音讯", "audio/ogg"),

    OGV("ogv", "OGG视频", "video/ogg"),

    OGX("ogx", "OGG", "application/ogg"),

    OPUS("opus", "OPUS音频", "audio/opus"),

    OTF("otf", "otf字体", "font/otf"),

    PNG("png", "便携式网络图形", "image/png"),

    PDF("pdf", "Adobe 可移植文档格式(PDF)", "application/pdf"),

    PHP("php", "php", "application/x-httpd-php"),

    PPT("ppt", "Microsoft PowerPoint", "application/vnd.ms-powerpoint"),

    PPTX("pptx", "Microsoft PowerPoint(OpenXML)", "application/vnd.openxmlformats-officedocument.presentationml.presentation"),

    RAR("rar", "RAR档案", "application/vnd.rar"),

    RTF("rtf", "富文本格式", "application/rtf"),

    SH("sh", "Bourne Shell脚本", "application/x-sh"),

    SVG("svg", "可缩放矢量图形(SVG)", "image/svg+xml"),

    SWF("swf", "小型Web格式(SWF)或Adobe Flash文档", "application/x-shockwave-flash"),

    TAR("tar", "磁带存档(TAR)", "application/x-tar"),

    TIF("tif", "标记图像文件格式(TIFF)", "image/tiff"),

    TIFF("tiff", "标记图像文件格式(TIFF)", "image/tiff"),

    TS("ts", "MPEG传输流", "video/mp2t"),

    TTF("ttf", "ttf字体", "font/ttf"),

    TXT("txt", "文本(通常为ASCII或ISO 8859- n", "text/plain"),

    VSD("vsd", "微软Visio", "application/vnd.visio"),

    WAV("wav", "波形音频格式", "audio/wav"),

    WEBA("weba", "WEBM音频", "audio/webm"),

    WEBM("webm", "WEBM视频", "video/webm"),

    WEBP("webp", "WEBP图像", "image/webp"),

    WOFF("woff", "Web开放字体格式(WOFF)", "font/woff"),

    WOFF2("woff2", "Web开放字体格式(WOFF)", "font/woff2"),

    XHTML("xhtml", "XHTML", "application/xhtml+xml"),

    XLS("xls", "微软Excel", "application/vnd.ms-excel"),

    XLSX("xlsx", "微软Excel(OpenXML)", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),

    XML("xml", "XML", "application/xml"),

    XUL("xul", "XUL", "application/vnd.mozilla.xul+xml"),

    ZIP("zip", "ZIP", "application/zip"),

    MIME_3GP("3gp", "3GPP audio/video container", "video/3gpp"),

    MIME_3GP_WITHOUT_VIDEO("3gp", "3GPP audio/video container doesn't contain video", "audio/3gpp2"),

    MIME_3G2("3g2", "3GPP2 audio/video container", "video/3gpp2"),

    MIME_3G2_WITHOUT_VIDEO("3g2", "3GPP2 audio/video container  doesn't contain video", "audio/3gpp2"),

    MIME_7Z("7z", "7-zip存档", "application/x-7z-compressed");

   //扩展名
    private final String extension;
    //说明
    private final String explain;
    //contentType/mime类型
    private final String mimeType;

    /**
     * @param extension 上传的文件扩展名
     * @param explain   类型说明
     * @param mimeType  Mime对应的类型
     */
    MimeTypeEnum(String extension, String explain, String mimeType) {
        this.extension = extension;
        this.explain = explain;
        this.mimeType = mimeType;
    }

    /**
     * 通过扩展名获取枚举类型
     *
     * @param extension 扩展名
     * @return 枚举类
     */
    public static MimeTypeEnum getByExtension(String extension) {
        if (StringUtils.isEmpty(extension)) {
            return null;
        }
        for (MimeTypeEnum typesEnum : MimeTypeEnum.values()) {
            if (extension.replace(".", "").equalsIgnoreCase(typesEnum.getExtension())) {
                return typesEnum;
            }
        }
        return null;
    }

    /**
     * Content-Type常用对照
     * 根据后缀获取Mime
     *
     * @param fileType 扩展名
     * @return mime类型
     */
    public static String getContentType(String fileType) {
        MimeTypeEnum mimeTypeEnum = MimeTypeEnum.getByExtension(fileType);
        if (mimeTypeEnum != null) {
            return mimeTypeEnum.getMimeType();
        }
        return "application/octet-stream";
    }
    public static void main(String[] args) throws Exception {

        MimeTypeEnum mimeTypeEnum = MimeTypeEnum.getByExtension("zip");
        System.out.println(mimeTypeEnum.getMimeType());
    }
}

nginx配置

需要nginx配置的可以按如下配置

# 此时的访问地址: 
server {
    listen 80;        
    server_name minio.home.com;
    client_max_body_size 20M;
    #PROXY-START/
    location /
    {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;

        proxy_connect_timeout 300;
        # Default is HTTP/1, keepalive is only enabled in HTTP/1.1
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        chunked_transfer_encoding off;

        proxy_pass http://localhost:9000; 
        # If you are using docker-compose this would be the hostname i.e. minio
        # Health Check endpoint might go here. See https://www.nginx.com/resources/wiki/modules/healthcheck/
        # /minio/health/live;
    }
    #PROXY-END/
}

访问权限

minio安装与java sdk_第2张图片
访问出现如上界面需放开权限
minio安装与java sdk_第3张图片
minio安装与java sdk_第4张图片
minio安装与java sdk_第5张图片
此时为无权限,具体权限可在以下位置设置
minio安装与java sdk_第6张图片

sts 授权

参考文档

步骤:
1.minio控制台创建 Policies
2.minio控制台创建用户,选择对应的Policies
3.java代码

String policy = "{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Action\": [\n" +
                "                \"s3:*\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";
AssumeRoleProvider assumeRoleProvider = new AssumeRoleProvider("http://127.0.0.1:9000",
                "test",
                "12345678",
                3600,
                policy,
                null, null,
                "roleSessionName", null, null
        );
        Credentials fetch = assumeRoleProvider.fetch();
        StaticProvider staticProvider = new StaticProvider(fetch.accessKey(), fetch.secretKey(), fetch.sessionToken());
        MinioClient client = MinioClient.builder().endpoint("http://127.0.0.1:9000").credentialsProvider(staticProvider).build();
// 然后走上传

你可能感兴趣的:(java小记,工作小结,java,minio)