minio的部署以及java代码整合

  我使用的是docker安装,这里不多说,首先进入linux系统

安装docker   如果出现Could not resolve host: yum.dockerproject.org; Unknown error  则删除/etc/yum.repos.d下的有关docker文件

拉取minio镜像
查看docker镜像  docker search minio
拉取docker镜像  docker pull minio/minio


# 先创建minio 文件存放的位置
mkdir -p /opt/docker/minio/data

5001图形化界面的端口
# 启动并指定端口
docker run \
  -p 5000:9000 \
  -p 5001:5001 \
  --name minio \
  -v /opt/docker/minio/data:/data \
  -e "MINIO_ROOT_USER=自己的登录minio的账号(自定义)" \
  -e "MINIO_ROOT_PASSWORD=自己登录minio账号的密码(自定义)" \
  -d minio/minio server /data --console-address ":5001"
 
# 设置为和 docker 绑定启动,docker 启动则 minio 就启动
docker update --restart=always


需要时间一致性
yum -y install ntp ntpdate
ntpdate 0.asia.pool.ntp.org
hwclock --systohc

桶的名称设置,访问文件的类型改为公共的,否者访问文件地址时会报错

 

在pom文件中需要添加依赖

<dependency>
        <groupId>io.minio</groupId>
         <artifactId>minio</artifactId>
         <version>7.1.0</version>
</dependency>

首先在yml中添加

minio:
  accessKey: 自己设置的账号
  secretKey: 自己设置的密码
  bucket: 桶的名称
  endpoint: http://minio部署的系统ip地址:5000 
  readPath: http://minio部署的系统ip地址:5000 

         MinioConfig类

package com.example.config;

import com.example.server.FileStorageService;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Data
@Configuration
@EnableConfigurationProperties({MinIOConfigProperties.class})
//当引入FileStorageService接口时
@ConditionalOnClass(FileStorageService.class)
public class MinIOConfig {

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    @Bean
    public MinioClient buildMinioClient() {
        return MinioClient
                .builder()
                .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())
                .endpoint(minIOConfigProperties.getEndpoint())
                .build();
    }
}

MinioConfigProperties类

package com.example.config;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.Serializable;

@Data
@ConfigurationProperties(prefix = "minio")  // 文件上传 配置前缀file.oss
public class MinIOConfigProperties implements Serializable {

    private String accessKey;
    private String secretKey;
    private String bucket;
    private String endpoint;
    private String readPath;
}

FileStorageService类

package com.example.server;

import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author itheima
 */
public interface FileStorageService {


    /**
     *  上传图片文件
     * @param prefix  文件前缀
     * @param filename  文件名
     * @param inputStream 文件流
     * @return  文件全路径
     */
    public String uploadImgFile(String prefix, String filename,InputStream inputStream);

    /**
     *  上传html文件
     * @param prefix  文件前缀
     * @param filename   文件名
     * @param inputStream  文件流
     * @return  文件全路径
     */
    public String uploadHtmlFile(String prefix, String filename,InputStream inputStream);

    /**
     * 删除文件
     * @param pathUrl  文件全路径
     */
    public void delete(String pathUrl);

    /**
     * 下载文件
     * @param pathUrl  文件全路径
     * @return
     *
     */
    public byte[]  downLoadFile(String pathUrl) throws IOException;

    /**
     * 上传文件
     */
    String uploadFile(MultipartFile file);

}

FileStorageServiceImpl

package com.example.server.impl;


import com.example.config.MinIOConfig;
import com.example.config.MinIOConfigProperties;
import com.example.server.FileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@EnableConfigurationProperties(MinIOConfigProperties.class)
@Import(MinIOConfig.class)
@Component
public class MinIOFileService implements FileStorageService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    private final static String separator = "/";

    /**
     * @param dirPath
     * @param filename  yyyy/mm/dd/file.jpg
     * @return
     */
    public String builderFilePath(String dirPath,String filename) {
        StringBuilder stringBuilder = new StringBuilder(50);
        if(!StringUtils.isEmpty(dirPath)){
            stringBuilder.append(dirPath).append(separator);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String todayStr = sdf.format(new Date());
        stringBuilder.append(todayStr).append(separator);
        stringBuilder.append(filename);
        return stringBuilder.toString();
    }

    /**
     *  上传图片文件
     * @param prefix  文件前缀
     * @param filename  文件名
     * @param inputStream 文件流
     * @return  文件全路径
     */
    @Override
    public String uploadImgFile(String prefix, String filename,InputStream inputStream) {
        String filePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType("image/jpg")
                    .bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)
                    .build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
            urlPath.append(separator+minIOConfigProperties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        }catch (Exception ex){
            log.error("minio put file error.",ex);
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) {
        return null;
    }


    /**
     * 上传pdf文件
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {

        //获取文件的名称
        String originalFilename = file.getOriginalFilename();
        //获取文件的前缀
        String caselsh = originalFilename.substring(0,originalFilename.lastIndexOf("."));

        String filePath = builderFilePath(caselsh, originalFilename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType(file.getContentType())
                    .bucket(minIOConfigProperties.getBucket()).stream(file.getInputStream(), file.getInputStream().available(),-1)
                    .build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
            urlPath.append(separator+minIOConfigProperties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        }catch (Exception ex){
            log.error("minio put file error.",ex);
            ex.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
    }

    /**
     * 删除文件
     * @param pathUrl  文件全路径
     */
    @Override
    public void delete(String pathUrl) {
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
        int index = key.indexOf(separator);
        String bucket = key.substring(0,index);
        String filePath = key.substring(index+1);
        // 删除Objects
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();
        try {
            minioClient.removeObject(removeObjectArgs);
        } catch (Exception e) {
            log.error("minio remove file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();
        }
    }


    /**
     * 下载文件
     * @param pathUrl  文件全路径
     * @return  文件流
     *
     */
    @Override
    public byte[] downLoadFile(String pathUrl) throws IOException {
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
        int index = key.indexOf(separator);
        String bucket = key.substring(0,index);
        String filePath = key.substring(index+1);
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(minIOConfigProperties.getBucket())
                    .object(filePath)
                    .build());
        } catch (Exception e) {
            log.error("minio down file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}

colltroller

package com.example.controller;

import com.example.pojo.AsyncTest;
import com.example.pojo.RuntimeRunThread;
import com.example.server.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.websocket.server.PathParam;
import java.io.*;
import java.net.URL;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class minioTest {

    /*@Autowired
    private ScpClientTest scpClientTest;*/

    @Autowired
    private FileStorageService service;

    @Autowired
    private AsyncTest asyncTest;

    @GetMapping("/download")
    public void download(@PathParam("pathUrl") String pathUrl) throws Exception {
        byte[] bytes = service.downLoadFile(pathUrl);

        File file = new File("D:\\yitouxin");
        if (!file.exists()) {
            file.mkdirs();
        }

        File file1 = new File(file, UUID.randomUUID() + ".pdf");

        URL url = new URL(pathUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }

        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(file1));
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        out.close();
        in.close();


        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.close();
    }

    /**
     * 下载文件
     *
     * @param pathUrl
     * @throws IOException
     *//*
    @GetMapping("download")
    public void download(@RequestParam("filePath") String filePath, HttpServletResponse response) throws IOException {
        if (filePath==null){

        }

        *//*String fileNmae = "你好啊";
        String name=new String(fileNmae.getBytes("gbk"),"utf-8");*//*

        byte[] bytes = service.downLoadFile(filePath);
        //设置相应头Content-Type  指定文件的类型
        //设置相应头Content-Disposition  指定文件以附件的形式保存
        response.setHeader("Content-Type","application/pdf");
        response.setHeader("Content-Disposition","attachment;filename="+文件名称);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.close();


    }*/

   /* @GetMapping("ScpClient")
    public void ScpClient(@RequestParam("path") String path){
        scpClientTest.test(path);
    }*/
    @GetMapping("/downloadImg")
    public void downloadImg(@PathParam("pathUrl") String pathUrl) throws IOException {
        byte[] bytes = service.downLoadFile(pathUrl);

        File file = new File("D:\\yitouxin\\" + UUID.randomUUID() + ".jpg");

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.close();
    }

    @GetMapping("/downloadMp4")
    public void downloadMp4(@PathParam("pathUrl") String pathUrl) throws IOException {
        byte[] bytes = service.downLoadFile(pathUrl);

        File file = new File("D:\\yitouxin\\" + UUID.randomUUID() + ".MP4");

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.close();
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public void upload(@RequestBody MultipartFile file) throws IOException {
        String s = service.uploadFile(file);
        System.out.println(s);
    }

    /**
     * 根据和文件路径删除文件
     */
    @DeleteMapping("/delete")
    public void delete(@PathParam("pathUrl") String pathUrl) {
        service.delete(pathUrl);
    }

    @GetMapping("/scpfile")
    public void scpfile() {
        asyncTest.test();
    }


}

时间太长忘记参考哪位博主的,如果看到可以添加或者删除.

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Java部署MinIO,您需要按照以下步骤操作: 1. 首先,您需要在Java项目中添加MinIO的依赖项。您可以在Maven或Gradle配置文件中添加以下依赖项: Maven: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>RELEASE.2021-03-25T23-39-59Z</version> </dependency> ``` Gradle: ``` implementation 'io.minio:minio:RELEASE.2021-03-25T23-39-59Z' ``` 2. 然后,您需要在Java代码中使用MinIO的API进行连接和操作。您可以使用以下示例代码来连接到MinIO服务器,并创建、读取和删除存储桶: ```java import io.minio.MinioClient; import io.minio.errors.MinioException; public class MinioExample { public static void main(String[] args) { try { // 创建一个MinIO客户端对象 MinioClient minioClient = new MinioClient("http://localhost:9000", "accessKey", "secretKey"); // 创建一个新的存储桶 minioClient.makeBucket("mybucket"); // 上传文件到存储桶 minioClient.putObject("mybucket", "myobject", "/path/to/file"); // 下载文件 minioClient.getObject("mybucket", "myobject", "/path/to/downloaded/file"); // 删除文件 minioClient.removeObject("mybucket", "myobject"); // 删除存储桶 minioClient.removeBucket("mybucket"); } catch (MinioException e) { // 处理MinIO异常 e.printStackTrace(); } } } ``` 请注意,您需要将上述代码中的"accessKey"和"secretKey"替换为您自己的MinIO凭据,并将"http://localhost:9000"替换为您的MinIO服务器地址。 这是一个简单的MinIO Java示例,您可以根据您的需求进行扩展和定制。 这些步骤会帮助您在Java部署和使用MinIO。根据您的具体需求,您可以进一步了解MinIO的API文档以及其他高级功能和配置选项。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [开源minio-AWS-S3存储的部署java操作](https://blog.csdn.net/liuyunshengsir/article/details/120266682)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [对象存储 minio windows服务端版本:2022-05-23T18-45-11Z](https://download.csdn.net/download/libie_lt/85456744)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值