我正在使用SQL Azure for Blob元数据存储和Azure Blob存储来实现实际的blob。通过在环境TransactionScope中登记这些操作来实现Blob创建/删除。到目前为止一切正常但我想知道是否有人可以推荐对删除操作的优化(参见下面的源代码),这可能会消除下载blob内容以便回滚的要求。
public class CloudBlobDeletionEnlistment : CloudBlobBaseEnlistment,
IEnlistmentNotification,
IDisposable
{
public CloudBlobDeletionEnlistment(Guid ownerId, string blobId, CloudBlobContainer container, Logger logger, IUserUploadActivity currentUploadActivity)
{
ctx = new Context { OwnerId = ownerId, BlobId = blobId, Container = container, Logger = logger, CurrentUploadActivity = currentUploadActivity };
}
public ~CloudBlobDeletionEnlistment()
{
Dispose(false);
}
public class Context
{
public Guid OwnerId;
public string BlobId;
public string ContentFileName;
public string MimeType;
public bool IsCompressed;
public CloudBlobContainer Container;
public Logger Logger;
public IUserUploadActivity CurrentUploadActivity;
}
private readonly Context ctx;
private CloudBlob blob;
public void Prepare(PreparingEnlistment preparingEnlistment)
{
blob = ctx.Container.GetBlobReference(ctx.BlobId);
// save backup information
ctx.ContentFileName = Path.GetTempFileName();
blob.DownloadToFile(ctx.ContentFileName);
blob.FetchAttributes();
ctx.MimeType = blob.Metadata[Constants.BlobMetaAttributeContentType];
ctx.IsCompressed = bool.Parse(blob.Metadata[Constants.BlobMetaAttributeCompressed]);
// delete it
blob.DeleteIfExists();
// done
preparingEnlistment.Prepared();
}
public void Commit(Enlistment enlistment)
{
Cleanup();
// done
enlistment.Done();
}
public void Rollback(Enlistment enlistment)
{
if (blob != null)
{
try
{
blob.UploadFile(ctx.ContentFileName);
blob.Metadata[Constants.BlobMetaAttributeContentType] = ctx.MimeType;
blob.Metadata[Constants.BlobMetaAttributeCompressed] = ctx.IsCompressed.ToString();
blob.SetMetadata();
}
finally
{
Cleanup();
}
}
else Cleanup();
// done
enlistment.Done();
}
public void InDoubt(Enlistment enlistment)
{
Cleanup();
enlistment.Done();
}
void Cleanup()
{
// delete the temporary file holding the blob content
if (!string.IsNullOrEmpty(ctx.ContentFileName) && File.Exists(ctx.ContentFileName))
{
File.Delete(ctx.ContentFileName);
ctx.ContentFileName = null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
}
// free native resources if there are any.
Cleanup();
}
#endregion
}
答案 0 :(得分:1)
这对我来说似乎不是一种安全的回滚机制 - 上传可能会失败,如果发生这种情况,那么您的数据一致性就会被破坏。
如果通过将其名称放入数据库中的ToBeDeleted
表中来删除blob,然后设置一些常规作业会不时删除这些blob,那该怎么办?
答案 1 :(得分:0)
在我看来,您希望创建一个blob并在单个事务上下文中创建元数据。这是不可能的。你的程序逻辑必须“成为交易”。
这同样适用于删除逻辑。