通过从数据库加载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的场景。

相关推荐
科技小花33 分钟前
全球化深水区,数据治理成为企业出海 “核心竞争力”
大数据·数据库·人工智能·数据治理·数据中台·全球化
X56612 小时前
如何在 Laravel 中正确保存嵌套动态表单数据(主服务与子服务)
jvm·数据库·python
虹科网络安全3 小时前
艾体宝干货|数据复制详解:类型、原理与适用场景
java·开发语言·数据库
2301_771717213 小时前
解决mysql报错:1406, Data too long for column
android·数据库·mysql
小江的记录本3 小时前
【Kafka核心】架构模型:Producer、Broker、Consumer、Consumer Group、Topic、Partition、Replica
java·数据库·分布式·后端·搜索引擎·架构·kafka
dvjr cloi4 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
dFObBIMmai4 小时前
MySQL主从同步中大事务导致的延迟_如何拆分大事务优化同步
jvm·数据库·python
szccyw04 小时前
mysql如何限制特定存储过程执行权限_MySQL存储过程安全访问
jvm·数据库·python
czlczl200209254 小时前
利用“延迟关联”优化 MySQL 巨量数据的深分页查询
数据库·mysql
ACP广源盛139246256735 小时前
IX8024与科学大模型的碰撞@ACP#筑牢科研 AI 算力高速枢纽分享
运维·服务器·网络·数据库·人工智能·嵌入式硬件·电脑