MINIO部署

一、MINIO单机部署

Linux下载地址:https://min.io/download#/linux

  1. 服务器创建新的文件夹;
    mkdir -p /home/minio/data
  2. 上传下载好的minio文件,到指定的目录下/home/minio/data

  3. 执行命令;

    chmod +x minio    //给予权限
    export MINIO_ACCESS_KEY=minioadmin   //创建账号
    export MINIO_SECRET_KEY=minioadmin   //创建密码
  4. 启动minio;
    nohup ./minio server  --address :9000 --console-address :9001 /home/minio/data > /home/minio/data/minio.log &

    自定义端口方式:自定义启动端口号以及控制台端口号,不设置则控制台会自动配置其他端口号,非常不方便

  5. 查看状态;

    ps -  ef|grep   minio
  6. 至此安装启动完成;
  7. 访问:127.0.0.1:9001/(注意:端口是控制台的端口);

  8. 输入步骤3设置的账号密码,进入到了管理页面;
  9. 设置桶,创建桶,在服务器中会生成一个和桶名称相同的文件夹;

  10. 设置桶规则;修改权限public,设置规则为readwrite;
  11. 测试上传文件到桶里边;
  12. 上传完文件之后在服务器的桶中会生成一个文件

二、JAVA集成

1) pom.xml导入相关依赖;

<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.3.5</version>
</dependency>
<!--OK Http-->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>

2)配置文件中增加配置信息;

minio:
  endpoint: http://127.0.0.1:9000
  accesskey: minioadmin             #用户名
  secretKey: minioadmin             #密码
  bucketName: files                  #桶名称

3)配置创建实体类;

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProp {
    /**
     * 连接url
     */
    private String endpoint;
    /**
     * 用户名
     */
    private String accesskey;
    /**
     * 密码
     */
    private String secretKey;

    /**
     * 桶名称
     */
    private String bucketName;

}

4)创建minioconfig;

@Configuration
@EnableConfigurationProperties(MinioProp.class)
public class MinioConfig {
    @Autowired
    private MinioProp minioProp;

    @Bean
    public MinioClient minioClient(){
        MinioClient minioClient = MinioClient.builder().endpoint(minioProp.getEndpoint()).
                credentials(minioProp.getAccesskey(), minioProp.getSecretKey()).region("china").build();
        return minioClient;
    }

}

5)编写minioUtil类;

上传:

public JSONObject uploadFile(MultipartFile file) throws Exception {
    JSONObject res = new JSONObject();
    res.put("code", 0);
    // 判断上传文件是否为空
    if (null == file || 0 == file.getSize()) {
        res.put("msg", "上传文件不能为空");
        return res;
    }
    InputStream is=null;
    try {
        // 判断存储桶是否存在
        createBucket(minioProp.getBucketName());
        // 文件名
        String originalFilename = file.getOriginalFilename();
        // 新的文件名 = 存储桶名称_时间戳.后缀名
        String fileName = minioProp.getBucketName() + "_" + IdUtil.getId() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 开始上传
        is=file.getInputStream();
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProp.getBucketName())
                .object(fileName)
                .contentType(file.getContentType())
                .stream(is, is.available(), -1)
                .build();
        minioClient.putObject(putObjectArgs);

        res.put("code", 1);
        res.put("msg",  minioProp.getBucketName() + "/" + fileName);
        res.put("bucket", minioProp.getBucketName());
        res.put("fileName", fileName);
        return res;
    }  catch (Exception e) {
        e.printStackTrace();
        log.error("上传文件失败:{}", e.getMessage());
    }finally {
        is.close();
    }
    res.put("msg", "上传失败");
    return res;
}

下载:

public void downLoad(String fileName,String realFileName, HttpServletResponse response, HttpServletRequest request) {
    InputStream is=null;
    OutputStream os =null;
    try {
        is=getObjectInputStream(fileName,minioProp.getBucketName());
        if(is!=null){
            byte buf[] = new byte[1024];
            int length = 0;
            String codedfilename = "";
            String agent = request.getHeader("USER-AGENT");
            System.out.println("agent:" + agent);
            if ((null != agent && -1 != agent.indexOf("MSIE")) || (null != agent && -1 != agent.indexOf("Trident"))) {
                String name = URLEncoder.encode(realFileName, "UTF8");
                codedfilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                codedfilename = new String(realFileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                codedfilename = new String(realFileName.getBytes("UTF-8"), "iso-8859-1");
            }
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName.substring(realFileName.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            os = response.getOutputStream();
            // 输出文件
            while ((length = is.read(buf)) > 0) {
                os.write(buf, 0, length);
            }
            // 关闭输出流
            os.close();

        }else{
            log.error("下载失败");
        }
    }catch (Exception e){
        e.printStackTrace();
        log.error("错误:"+e.getMessage());
    }finally {
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(os!=null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

删除:

public void deleteObject(String objectName) {
    try {
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                .bucket(minioProp.getBucketName())
                .object(objectName)
                .build();
        minioClient.removeObject(removeObjectArgs);
    }catch (Exception e){
        log.error("错误:"+e.getMessage());
    }
}

查看:一个url

例如127.0.0.1:9000/files/files_1660635187005.png;

格式:ip:端口/桶/文件在桶里的真实名字;

完整的util类:



import com.alibaba.fastjson2.JSONObject;
import com.crcc.statistics.common.entity.MinioProp;
import io.minio.*;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author smallhou
 * @Date 2022-08-15 14:31
 * @Version V1.0
 */
@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProp minioProp;

    /**
     * @Author smallhou
     * @Description //TODO 判断桶存在不存在,不存在创建桶
     * @Date 10:49 2022-08-16
     * @Param [bucketName]
     * @return void
     **/
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

    }

    @SneakyThrows
    public InputStream getObjectInputStream(String objectName,String bucketName){
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        return minioClient.getObject(getObjectArgs);
    }


    public JSONObject uploadFile(MultipartFile file) throws Exception {
        JSONObject res = new JSONObject();
        res.put("code", 0);
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            res.put("msg", "上传文件不能为空");
            return res;
        }
        InputStream is=null;
        try {
            // 判断存储桶是否存在
            createBucket(minioProp.getBucketName());
            // 文件名
            String originalFilename = file.getOriginalFilename();
            // 新的文件名 = 存储桶名称_时间戳.后缀名
            String fileName = minioProp.getBucketName() + "_" + IdUtil.getId() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 开始上传
            is=file.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProp.getBucketName())
                    .object(fileName)
                    .contentType(file.getContentType())
                    .stream(is, is.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);

            res.put("code", 1);
            res.put("msg",  minioProp.getBucketName() + "/" + fileName);
            res.put("bucket", minioProp.getBucketName());
            res.put("fileName", fileName);
            return res;
        }  catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件失败:{}", e.getMessage());
        }finally {
            is.close();
        }
        res.put("msg", "上传失败");
        return res;
    }

    public void downLoad(String fileName,String realFileName, HttpServletResponse response, HttpServletRequest request) {
        InputStream is=null;
        OutputStream os =null;
        try {
            is=getObjectInputStream(fileName,minioProp.getBucketName());
            if(is!=null){
                byte buf[] = new byte[1024];
                int length = 0;
                String codedfilename = "";
                String agent = request.getHeader("USER-AGENT");
                System.out.println("agent:" + agent);
                if ((null != agent && -1 != agent.indexOf("MSIE")) || (null != agent && -1 != agent.indexOf("Trident"))) {
                    String name = URLEncoder.encode(realFileName, "UTF8");
                    codedfilename = name;
                } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                    codedfilename = new String(realFileName.getBytes("UTF-8"), "iso-8859-1");
                } else {
                    codedfilename = new String(realFileName.getBytes("UTF-8"), "iso-8859-1");
                }
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName.substring(realFileName.lastIndexOf("/") + 1), "UTF-8"));
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                // 输出文件
                while ((length = is.read(buf)) > 0) {
                    os.write(buf, 0, length);
                }
                // 关闭输出流
                os.close();

            }else{
                log.error("下载失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("错误:"+e.getMessage());
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void deleteObject(String objectName) {
        try {
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                    .bucket(minioProp.getBucketName())
                    .object(objectName)
                    .build();
            minioClient.removeObject(removeObjectArgs);
        }catch (Exception e){
            log.error("错误:"+e.getMessage());
        }
    }


}

三、总结:

部署相对简单,JAVA集成快,上手更容易;

  • 5
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值