通过从数据库加载MinIO配置并初始化MinioClient,spring boot之Minio上传

java 复制代码
package org.springblade.modules.resource.endpoint;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.PutObjectArgs;
import io.minio.MinioClient;
import org.springblade.modules.resource.entity.Oss;
import org.springblade.modules.resource.mapper.OssMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class MinioService {



	private String endpoint ;


	private String accessKey ;


	private String secretKey ;
	private String bucketName ;

	private MinioClient minioClient;


	@Resource
	private OssMapper ossMapper;
	/**
	 * 初始化方法:从数据库加载配置并创建 MinioClient
	 */
	@PostConstruct
	public void init() {
		// 从数据库查询配置
		Oss config = ossMapper.selectOne(Wrappers.lambdaQuery(Oss.class)
			.eq(Oss::getOssCode, "minio"));

		if (config == null) {
			throw new RuntimeException("未找到 MinIO 配置!");
		}

		// 赋值配置
		this.endpoint = config.getEndpoint();
		this.accessKey = config.getAccessKey();
		this.secretKey = config.getSecretKey();
		this.bucketName = config.getBucketName();

		// 初始化 MinioClient(仅需创建一次)
		this.minioClient = MinioClient.builder()
			.endpoint(endpoint)
			.credentials(accessKey, secretKey)
			.build();

		// 确保存储桶存在
		try {
			createBucketIfNotExists(bucketName);
		} catch (Exception e) {
			throw new RuntimeException("初始化存储桶失败", e);
		}
	}

	/**
	 * 上传文件到 MinIO
	 */
	public String uploadFile(String name,MultipartFile file) throws Exception {
		// 确保存储桶存在
		createBucketIfNotExists(bucketName);

		// 生成带时间戳的文件名
		String fileName = generateFileNameWithTimestamp(name);

		// 上传文件
		try (InputStream stream = file.getInputStream()) {
			PutObjectArgs args = PutObjectArgs.builder()
				.bucket(bucketName)
				.object(fileName)
				.stream(stream, stream.available(), -1)
				.contentType(file.getContentType())
				.build();

			MinioClient minioClient = new MinioClient.Builder().endpoint(endpoint)
				.credentials(accessKey, secretKey)
				.build();
			minioClient.putObject(args);
			// 拼接 domin+ bucketName + fileName
			String fileLink = endpoint + "/" + bucketName + "/" + fileName;
			return fileLink;
		}
	}

	/**
	 * 生成带时间戳的文件名
	 */
	private String generateFileNameWithTimestamp(String originalFilename) {
		if (originalFilename == null || originalFilename.isEmpty()) {
			return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".unknown";
		}

		String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
		int dotIndex = originalFilename.lastIndexOf('.');

		if (dotIndex > 0) {
			return originalFilename.substring(0, dotIndex) + "_" + timestamp + originalFilename.substring(dotIndex);
		}

		return originalFilename + "_" + timestamp;
	}

	/**
	 * 创建存储桶(如果不存在)
	 */
	private void createBucketIfNotExists(String bucketName) throws Exception {
		boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
		if (!exists) {
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
		}
	}
}

该代码实现了一个基于MinIO的文件上传服务。通过从数据库加载MinIO配置并初始化MinioClient,确保存储桶存在后,可以将文件上传到MinIO服务器。文件上传时,生成带时间戳的文件名,并将文件流上传到指定存储桶。上传成功后,返回文件的访问链接。代码通过@PostConstruct注解在服务初始化时自动加载配置,确保MinioClient的创建和存储桶的检查。整体功能包括文件上传、存储桶管理及文件名生成,适用于需要将文件存储到MinIO的场景。

相关推荐
hacker_LeeFei3 小时前
Windows 下配置 Redis 8.10.2 开机自启:一次踩坑全记录
数据库·windows·redis
这个DBA有点耶3 小时前
MySQL字符集与排序规则深入:索引失效的隐蔽场景与排查方法
数据库·mysql·代码规范
zl_dfq3 小时前
Redis 之 【持久化 与 事务】
数据库·redis
闲云自留地4 小时前
从下载到登录:MySQL 在两大系统上的完整安装教程
数据库·mysql
SelectDB技术团队5 小时前
Apache Doris 高性能 Open Lake Variant 读写技术解析(含对比数据)
数据结构·数据库·clickhouse·日志·apache doris·selectdb·湖仓架构升级
一 乐5 小时前
博客管理系统|基于springboot + vue博客管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕设
茉莉玫瑰花茶5 小时前
GO [ 类型 ]
开发语言·数据库·golang
ClouGence5 小时前
开源数据库管理工具 CloudDM 4.3.0 发布,支持 SQL 收藏,多数据源语法支持大幅增强
数据库·oracle·sql server
Summer-Bright6 小时前
深度 | 壁仞1.74亿中标智算中心:国产GPU从能用跨进商用,但4.5亿的大单却因凑不齐三家废标了
数据库·ai·国产gpu
云安全助手6 小时前
自建接入VS聚合平台:企业 AI 调用的选型思路与迁移成本拆解
java·大数据·数据库·人工智能·ai大模型