MinIO的简单使用

通过docker拉取,详情请看docker篇

启动镜像

sudo docker run -dt   -p 9000:9000 -p 9001:9001   -v /etc/default/minio/minio.env:/etc/config.env   -e "MINIO_CONFIG_ENV_FILE=/etc/config.env"   --name "minio_local"   802bb0d1848f server /export --console-address ":9001"

Bucket相关的配置
在这里插入图片描述

Summary(概要):主要是展示当前bucket相关的配置。

Access Poilcy:一共有三个值,private,public,custom。私有代表需要通过验签且生成的url只有7天有效期。公共代表不需要验签通过http://127.0.0.1:端口/test/minio.jpg永久可以访问。自定义就是可以自己定义那些前缀是只读,那些前缀是读写的等等。这个在Anonymous里面可以配置。

Encyption: 就是配置是否加密。

Anonymous:配置Access Poilcy为custom,可以自己定义那些前缀是只读,那些前缀是读写的等等。

Events:事件,主要是给这个Bucket绑定那些事件通知,下面会讲到如何使用。

Lifecycle(生命周期):就是配置生命这个bucket的生命周期。

类型选择Expiry代表是过期直接删除,选择Transition就是过期后转移到目标存储服务器。需要搭配Tiering使用。

After:代表多少天后过期

Prefix:文件名前缀。

SpringBoot使用

        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.5.13</version>
        </dependency>
spring: 
  minio:
    endpoint: http://192.168.153.128:9000/
    accessKey: minio
    secretKey: minio1234
    bucketName: test
@Configuration
public class MinioConfig {

    @Value("${spring.minio.endpoint}")
    private String endpoint;

    @Value("${spring.minio.accessKey}")
    private String accessKey;

    @Value("${spring.minio.secretKey}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
}

    @PostMapping("/file")
    public String uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        InputStream fileInputStream = file.getInputStream();
        minioConfig.putObject(
                PutObjectArgs.builder()
                        .bucket("test") //bucket桶
                        .object(filename)	//文件名
                        .stream(fileInputStream, file.getSize(), -1) // 流和文件大小
                        .contentType(file.getContentType()) //文件类型
                        .build()
        );

        return "上传成功";
    }

工具类

package com.web.config;

import com.google.common.collect.Lists;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import javafx.scene.input.DataFormat;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MinioUtil {

    private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;

    @Autowired
    private MinioClient minio;

    @Autowired
    MinioConfig minioConfig;



    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public boolean bucketExists(String bucketName) {
        return minio.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    @SneakyThrows
    public boolean makeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return true;
        }

        minio.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        return true;
    }

    /**
     * 列出所有存储桶名称
     *
     * @return
     */
    @SneakyThrows
    public List<String> listBucketNames() {
        List<Bucket> list = listBuckets();
        return list.stream().filter(Objects::nonNull).map(o -> o.name()).collect(Collectors.toList());
    }

    /**
     * 列出所有存储桶
     *
     * @return
     */
    @SneakyThrows
    public List<Bucket> listBuckets() {
        return minio.listBuckets();
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public boolean removeBucket(String bucketName) {
        Iterable<Result<Item>> myObjects = listObjects(bucketName);
        for (Result<Item> result : myObjects) {
            Item item = result.get();
            // 有对象文件,则删除失败
            if (item.size() > 0) {
                return false;
            }
        }
        // 删除存储桶,注意,只有存储桶为空时才能删除成功。
        minio.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        return !bucketExists(bucketName);
    }


    /**
     * 在test桶里创建文件夹对象
     *
     * @param fileName
     */
    public void createFile(String fileName) {
        try {
            if (!bucketExists("test")) {
                //minio服务器创建桶
                makeBucket("test");
            }
            minio.putObject(
                    PutObjectArgs.builder().bucket("test").object(fileName).stream(
                                    new ByteArrayInputStream(new byte[]{}), 0, -1)
                            .build());
        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (InsufficientDataException e) {
            e.printStackTrace();
        } catch (InternalException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidResponseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (XmlParserException e) {
            e.printStackTrace();
        }
    }

    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public Iterable<Result<Item>> listObjects(String bucketName) {
        return minio.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public List<String> listObjectNames(String bucketName) {
        List<String> ret = Lists.newArrayList();
        Iterable<Result<Item>> myObjects = listObjects(bucketName);
        for (Result<Item> result : myObjects) {
            Item item = result.get();
            ret.add(item.objectName());
        }

        return ret;
    }

    /**
     * 文件上传
     *
     * @param bucketName
     * @param multipartFile
     */
    @SneakyThrows
    public ObjectWriteResponse putObject(String bucketName, MultipartFile multipartFile) {
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(multipartFile.getName())
                .contentType(multipartFile.getContentType())
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                .build();

        return minio.putObject(args);
    }

    /**
     * 通过InputStream上传对象
     *
     * @param bucketName  存储桶名称
     * @param objectName  存储桶里的对象名称
     * @param in          要上传的流
     * @param contentType 要上传的文件类型 MimeTypeUtils.IMAGE_JPEG_VALUE
     * @return
     */
    @SneakyThrows
    public ObjectWriteResponse putObject(String bucketName, String objectName, InputStream in, String contentType) {
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(getDataTime()+"/"+objectName)
                .contentType(contentType)
                .stream(in, in.available(), -1)
                .build();

        return minio.putObject(args);
    }

    public String getDataTime(){
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String date = localDate.format(df).toString();

        String replace = date.replace("-", "/");

        return replace;
    }
    
    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public InputStream getObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            return null;
        }

        StatObjectResponse resp = statObject(bucketName, objectName);
        return resp == null
                ? null
                : minio.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 获取对象的元数据
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public StatObjectResponse statObject(String bucketName, String objectName) {
        return !bucketExists(bucketName)
                ? null
                : minio.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    @SneakyThrows
    public void removeMinio(String fileName) {
        try {
            MinioClient minioClient = minioConfig.minioClient();
            minioClient.removeObject(RemoveObjectArgs.builder().bucket("test").object(fileName).build());
//            minioConfig.minioClient().removeObject(RemoveObjectArgs.builder().bucket("test").object(fileName).build());
//            minio.removeObject(RemoveObjectArgs.builder().bucket("test").object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取文件外链
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return url
     */
    @SneakyThrows
    public String getObjectURL(String bucketName, String objectName) {
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
//                .expiry(60 * 60 * 24)
                .build();
        return minio.getPresignedObjectUrl(build);
    }

}

controller

@PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public void upload(@RequestPart(value = "file",required = false) MultipartFile file,@RequestParam(value = "name",required = false) String name) throws IOException {
    ObjectWriteResponse response = minioUtil.putObject(minioConfig.getBucketName(), name,file.getInputStream(), file.getContentType());
    if (response != null){
        System.out.println("插入成功");
    }else {
        System.out.println("插入失败");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值