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

相关推荐
TDengine (老段)1 小时前
杨凌美畅用 TDengine 时序数据库,支撑 500 条产线 2 年历史数据追溯
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
葛小白14 小时前
C#数据类型:string简单使用
服务器·数据库·c#
污斑兔4 小时前
MongoDB的$sample是啥?
数据库·mongodb
马丁的代码日记5 小时前
MySQL InnoDB 行锁与死锁排查实战演示
数据库·mysql
拍客圈6 小时前
数据主站+副站做的设置
数据库
计算机学长felix7 小时前
基于SpringBoot的“面向校园的助力跑腿系统”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·后端
金仓拾光集7 小时前
__工艺数据管理的范式转变:金仓数据库替代MongoDB实操实践__
数据库·mongodb
xiaogg36788 小时前
redis-cluster集群配置部署
数据库·redis·缓存
运维小文8 小时前
MySQL高可用方案MIC&mysqlCluster+mysqlRouter
数据库·mysql·mic·mysql高可用·mysqlcluster·mysqlrouter
不剪发的Tony老师8 小时前
Redis Commander:一款基于Web、免费开源的Redis管理工具
数据库·redis