MasstransferExporter/MasstransferInfrastructure/Minio/MinioHelper.cs

119 lines
3.5 KiB
C#

using MasstransferCommon.Model.Entity;
using MasstransferInfrastructure.Database.Sqlite;
using Minio;
using Minio.DataModel.Args;
namespace MasstransferCommunicate.Minio;
/// <summary>
/// Minio工具类
/// </summary>
public class MinioHelper
{
private readonly IMinioClient _client;
private static MinioHelper? _instance;
private static readonly object Lock = new();
private static SqliteHelper _sqliteHelper = SqliteHelper.GetInstance();
private MinioHelper(string endpoint, string accessKey, string secretKey)
{
_client = new MinioClient()
.WithSSL()
.WithEndpoint(endpoint)
.WithCredentials(accessKey, secretKey)
.Build();
}
public static MinioHelper GetInstance()
{
lock (Lock)
{
var minio = _sqliteHelper.Query<MinioParams>("select * from minio_params limit 1").FirstOrDefault();
_instance ??= new MinioHelper(minio.MinioEndpoint, minio.MinioAccessKey, minio.MinioSecretKey);
return _instance;
}
}
/// <summary>
/// 判断bucket 是否存在
/// </summary>
/// <param name="bucketName"></param>
/// <returns></returns>
public async Task<bool> BucketExistsAsync(string bucketName)
{
return await _client.BucketExistsAsync(new BucketExistsArgs().WithBucket(bucketName));
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="bucketName"></param>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public async Task<string> UploadFileAsync(string bucketName, string fileName, string filePath)
{
try
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
Console.WriteLine($"正在上传文件: {fileName} 到 bucket: {bucketName}");
await _client.PutObjectAsync(new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName)
.WithFileName(filePath));
Console.WriteLine($"文件 {fileName} 上传成功");
return $"{bucketName}/{fileName}";
}
catch (Exception e)
{
Console.WriteLine($"文件上传失败: {e}");
return "";
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="bucketName"></param>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
public async Task DownloadFileAsync(string bucketName, string fileName, string filePath)
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
await _client.GetObjectAsync(new GetObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName)
.WithFile(filePath));
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="bucketName"></param>
/// <param name="fileName"></param>
public async Task DeleteFileAsync(string bucketName, string fileName)
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
await _client.RemoveObjectAsync(new RemoveObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName));
}
}