小工具知识网

当前位置: 首页 > 行业知识 > springboot如何快速接入minio对象存储

行业知识

springboot如何快速接入minio对象存储

2026-11-12 09:20:26 来源:互联网转载

1.在项目中添加 Minio 的依赖,在使用 Minio 之前,需要在项目中添加 Minio 的依赖。可以在 Maven 的 pom.xml 文件中添加以下依赖:

    io.minio    minio    7.0.2
2.在项目的配置文件中,添加minio服务器相关信息,这里使用的是application.yml文件:
minio:  host: http://mini0.dl.cn:9000  url: ${minio.host}/${minio.bucket}/  access-key: ***   #minio服务器上的access-key  secret-key: ***   #minio服务器上的secret-key  bucket: ***  #需要使用的桶的名称

3.在项目中编写一个名为 MinioConfig.java 的配置类,用于加载 application.yml文件中的minio配置信息,并初始化 Minio 的客户端,使用 Minio 客户端进行相关操作,例如上传文件、下载文件、删除文件等。

@Componentpublic class MinioConfig implements InitializingBean {    @Value(value = "${minio.bucket}")    private String bucket;    @Value(value = "${minio.host}")    private String host;    @Value(value = "${minio.url}")    private String url;    @Value(value = "${minio.access-key}")    private String accessKey;    @Value(value = "${minio.secret-key}")    private String secretKey;    private MinioClient minioClient;    @Override    public void afterPropertiesSet() throws Exception {        Assert.hasText(url, "Minio url 为空");        Assert.hasText(accessKey, "Minio accessKey为空");        Assert.hasText(secretKey, "Minio secretKey为空");        this.minioClient = new MinioClient(this.host, this.accessKey, this.secretKey);    }    /**     * 上传     */    public String putObject(MultipartFile multipartFile) throws Exception {        // bucket 不存在,创建        if (!minioClient.bucketExists(this.bucket)) {            minioClient.makeBucket(this.bucket);        }        try (InputStream inputStream = multipartFile.getInputStream()) {            // 上传文件的名称            String fileName = multipartFile.getOriginalFilename();            // PutObjectOptions,上传配置(文件大小,内存中文件分片大小)            PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);            // 文件的ContentType            putObjectOptions.setContentType(multipartFile.getContentType());            minioClient.putObject(this.bucket, fileName, inputStream, putObjectOptions);            // 返回访问路径            return this.url + UriUtils.encode(fileName, StandardCharsets.UTF_8);        }    }    /**     * 文件下载     */    public void download(String fileName, HttpServletResponse response){        // 从链接中得到文件名        InputStream inputStream;        try {            MinioClient minioClient = new MinioClient(host, accessKey, secretKey);            ObjectStat stat = minioClient.statObject(bucket, fileName);            System.out.println("stat = " + stat);            inputStream = minioClient.getObject(bucket, fileName);            response.setContentType(stat.contentType());            response.setCharacterEncoding("UTF-8");            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));            IOUtils.copy(inputStream, response.getOutputStream());            inputStream.close();        } catch (Exception e){            e.printStackTrace();            System.out.println("有异常:" + e);        }    }    /**     * 列出所有存储桶名称     *     * @return     * @throws Exception     */    public List listBucketNames()            throws Exception {        List bucketList = listBuckets();        List bucketListName = new ArrayList();        for (Bucket bucket : bucketList) {            bucketListName.add(bucket.name());        }        return bucketListName;    }    /**     * 查看所有桶     *     * @return     * @throws Exception     */    public List listBuckets()            throws Exception {        return minioClient.listBuckets();    }    /**     * 检查存储桶是否存在     *     * @param bucketName     * @return     * @throws Exception     */    public boolean bucketExists(String bucketName) throws Exception {        boolean flag = minioClient.bucketExists(bucketName);        if (flag) {            return true;        }        return false;    }    /**     * 创建存储桶     *     * @param bucketName     * @return     * @throws Exception     */    public boolean makeBucket(String bucketName)            throws Exception {        boolean flag = bucketExists(bucketName);        if (!flag) {            minioClient.makeBucket(bucketName);            return true;        } else {            return false;        }    }    /**     * 删除桶     *     * @param bucketName     * @return     * @throws Exception     */    public boolean removeBucket(String bucketName)            throws Exception {        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable myObjects = listObjects(bucketName);            for (Result 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     * @throws Exception     */    public Iterable listObjects(String bucketName) throws Exception {        boolean flag = bucketExists(bucketName);        if (flag) {            return minioClient.listObjects(bucketName);        }        return null;    }    /**     * 列出存储桶中的所有对象名称     *     * @param bucketName 存储桶名称     * @return     * @throws Exception     */    public List listObjectNames(String bucketName) throws Exception {        List listObjectNames = new ArrayList();        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable myObjects = listObjects(bucketName);            for (Result result : myObjects) {                Item item = result.get();                listObjectNames.add(item.objectName());            }        }        return listObjectNames;    }    /**     * 删除一个对象     *     * @param bucketName 存储桶名称     * @param objectName 存储桶里的对象名称     * @throws Exception     */    public boolean removeObject(String bucketName, String objectName) throws Exception {        boolean flag = bucketExists(bucketName);        if (flag) {            List objectList = listObjectNames(bucketName);            for (String s : objectList) {                if(s.equals(objectName)){                    minioClient.removeObject(bucketName, objectName);                    return true;                }            }        }        return false;    }    /**     * 文件访问路径     *     * @param bucketName 存储桶名称     * @param objectName 存储桶里的对象名称     * @return     * @throws Exception     */    public String getObjectUrl(String bucketName, String objectName) throws Exception {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            url = minioClient.getObjectUrl(bucketName, objectName);        }        return url;    }}

4.创建MinioController.java类,处理文件上传,下载,桶创建,删除等操作。

RestController@RequestMapping("minio")@Slf4jpublic class MinioController {    @Autowired    MinioConfig minioConfig;    // 上传    @PostMapping("/upload")    public Object upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {        return this.minioConfig.putObject(multipartFile);    }    //下载    @GetMapping("/download")    public void download(@RequestParam("fileName")String fileName, HttpServletResponse response) {           this.minioConfig.download(fileName,response);    }    // 列出所有存储桶名称    @PostMapping("/list")    public List list() throws Exception {        return this.minioConfig.listBucketNames();    }    // 创建存储桶    @PostMapping("/createBucket")    public boolean createBucket(String bucketName) throws Exception {        return this.minioConfig.makeBucket(bucketName);    }    // 删除存储桶    @PostMapping("/deleteBucket")    public boolean deleteBucket(String bucketName) throws Exception {        return this.minioConfig.removeBucket(bucketName);    }    // 列出存储桶中的所有对象名称    @PostMapping("/listObjectNames")    public List listObjectNames(String bucketName) throws Exception {        return this.minioConfig.listObjectNames(bucketName);    }    // 删除一个对象    @PostMapping("/removeObject")    public boolean removeObject(String bucketName, String objectName) throws Exception {        return this.minioConfig.removeObject(bucketName, objectName);    }    // 文件访问路径    @PostMapping("/getObjectUrl")    public String getObjectUrl(String bucketName, String objectName) throws Exception {        return this.minioConfig.getObjectUrl(bucketName, objectName);    }}

5.测试

上一篇:探索网站历史数据背后的故事,深度揭秘查询之旅!

下一篇:地铁怎么换回之前服务器?