Azure 存储“租赁” - 正确的异常方法

时间:2021-03-23 09:58:00

标签: c# .net-core azure-storage azure-storage-blobs

我正在开发 NET Core Web 应用程序,我正在使用 blob 来存储一些可以在请求期间修改的对象。我必须防止对一个对象进行多次并行访问,因此我将“租用”添加到我的存储集成中。 实际上,当我收到请求时,会从 blob 中获取一个对象,并租用一段时间。在请求结束时,此对象在存储中更新并删除租约 - 非常简单。 但什么是正确的异常处理? 当请求过程中发生一些异常时,我又遇到了这个问题,租约没有被释放。我试图实现释放到处置(在我控制从 blob 获取和租赁的某个类中)。但是当抛出未处理的异常时,这不会执行。 添加 try/catch/finally 对我来说似乎不干净。我的问题是你知道一些最常见的方法如何在最终请求上释放租约吗?谢谢

enter image description here

1 个答案:

答案 0 :(得分:0)

根据你的描述,我为你写了一个关于租约和中断租约的简单演示,试试下面的代码:

using System;
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Mvc;
using Azure.Storage.Blobs.Specialized;
using System.Threading;

namespace getSasTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class editBlob : ControllerBase
    {
        [HttpGet]
        public string get()
        {
            var connstr = "";
            var container = "";
            var blob = "";
            
            var blobClient = new BlobContainerClient(connstr,container).GetBlobClient(blob);

            var leaseClient = new BlobLeaseClient(blobClient);
            try
            {
                //auto break lease after 15s
                var duration = new TimeSpan(0, 0, 15);
                leaseClient.Acquire(duration, null);

            }
            //if some error occurs, request ends here
            catch (Azure.RequestFailedException e)
            {
               
                if (e.ErrorCode.Equals("LeaseAlreadyPresent"))
                {
                    return "Blob is under process,it will take some time,please try again later";
                }
                else
                {
                    return "some other Azure request errors:"+ e.Message;
                }

            }
            catch (Exception e) { 
                    return "some other errors:" + e.Message;
            }

            //mock time consumption to process blob
            Thread.Sleep(10000);

            //break relase first if process finishs in 15s.
            leaseClient.Break();

            return "Done";
        }
    }
}