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

相关推荐
九皇叔叔9 分钟前
【7】PostgreSQL 事务
数据库·postgresql
kk在加油12 分钟前
Mysql锁机制与优化实践以及MVCC底层原理剖析
数据库·sql·mysql
Kookoos29 分钟前
ABP VNext + Cosmos DB Change Feed:搭建实时数据变更流服务
数据库·分布式·后端·abp vnext·azure cosmos
hello 早上好1 小时前
MsSql 其他(2)
数据库·mysql
高压锅_12201 小时前
SQLAlchemy数据库连接密码特殊字符处理完全指南
数据库·mysql·django·sqlalchemy
Hello.Reader6 小时前
Redis 延迟监控深度指南
数据库·redis·缓存
ybq195133454316 小时前
Redis-主从复制-分布式系统
java·数据库·redis
好奇的菜鸟9 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
tan180°9 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
满昕欢喜9 小时前
SQL Server从入门到项目实践(超值版)读书笔记 20
数据库·sql·sqlserver