异步调用增加值的方法,避免重复

我尝试从AAA000-> ZZZ999调用创建ID的方法。该方法本身工作正常,但是我异步调用它,当同时创建2个或更多案例时,这会引起问题。最高值存储在数据库中(不必存储),我正在尝试这样做:

获取最高的当前值->使用我的方法将其递增->保存新的最高值->返回新的最高值。

在使用这种方法之前,我只是从Case表中获取最大值。

我已经考虑了几种方法来实现此目的,包括从AAA000-> ZZZ999播种数据库,并以postgres ID为增量查找“友好”值。但是,这似乎不是最佳的。

关于如何实现这一目标的任何建议将不胜感激:

代码概述:

.net核心微服务 CQRS 亚马逊SQS 轨道交通 自动贴图 中介

消费者

    public async Task Consume(ConsumeContext<EmailClassified> context)
    {
        var caseCommand = new CreateCaseFromEmailCommand(context.Message.Classification, context.Message.AiProbability, context.Message.Email);
        var newCase = await _mediator.Send(caseCommand);

        if (newCase != null)
        {
            // do something signalR
            await Task.CompletedTask;
        }
        else
        {
            // log error
            await Task.CompletedTask;

        }
    }

命令

public class CreateCaseFromEmailCommand : IRequest<Case>
{
    public string Classification { get; set; }
    public decimal AiProbability { get; set; }
    public CaseEmail Email { get; set; }

    public CreateCaseFromEmailCommand(string classification, decimal aiProbability, CaseEmail email)
    {
        Classification = classification;
        AiProbability = aiProbability;
        Email = email;
    }
}

处理程序

public class CreateCaseFromEmailCommandHandler : IRequestHandler<CreateCaseFromEmailCommand, Case>
{
    private readonly IMyDbContext _context;

    public CreateCaseFromEmailCommandHandler(IMyDbContext context)
    {
        _context = context;
    }

    public async Task<Case> Handle(CreateCaseFromEmailCommand request, CancellationToken cancellationToken)
    {
        try
        {
            NextIdHelper helper = new NextIdHelper(_context);
            string caseReference = helper.GetNextFriendlyId();


            var investor = _context.Set<Investor>()
                .FirstOrDefault(i => i.EmailAddress.ToLower() == request.Email.FromAddress.ToLower());
            var classification =  _context.Set<Classification>().Include(t => t.Team)
                .FirstOrDefault(c => c.Name.ToLower() == request.Classification.ToLower());
            var team = classification.Team;

            var entity = new Case()
            {
                FriendlyCaseId = caseReference,
                Summary = request.Email.Subject,
                Description = request.Email.Message,
                Priority = Priority.Medium,
                CaseStatus = CaseStatus.Open,
                CreatedDate = DateTime.Now,
                NextSla = DateTime.Now.AddDays(1),
                Investor = investor,
                UnknownInvestorEmail = investor == null ? request.Email.FromAddress : null,
                Classification = classification,
                Team = team,
                AiProbability = request.AiProbability,
                Emails = new List<CaseEmail> {request.Email}
            };

            _context.Set<Case>().Add(entity);

            await _context.SaveChangesAsync(cancellationToken);

            return entity;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

帮手

public class NextIdHelper
{
    private readonly IMyDbContext _context;
    public string Value { get; set; }

    public NextIdHelper(IMyDbContext context)
    {
        _context = context;
    }
    public string GetNextFriendlyId()
    {
        var nextValue = "";
        var highestId = _context.Set<MaxCaseReference>().FirstOrDefault();

        if (!string.IsNullOrWhiteSpace(Value))
        {
            nextValue = CalculateNextId(Value);
        }
        else
        {
            nextValue = CalculateNextId(highestId.Reference);
        }

        highestId.Reference = nextValue;
        Value = nextValue;

        _context.SaveChanges();

        return nextValue;
    }

    private string CalculateNextId(string currentId)
    {
        char[] characters = currentId.ToCharArray();
        int currNum = int.Parse(currentId.Substring(currentId.Length - 3));

        Tuple<char, char, char, int> id = new Tuple<char, char, char, int>(characters[0], characters[1], characters[2], currNum);

        var number = id.Item4 + 1;
        var c3 = id.Item3;
        var c2 = id.Item2;
        var c1 = id.Item1;

        if (number > 999)
        {
            number = 0;
            c3++;
            if (c3 > 'Z')
            {
                c3 = 'A';
                c2++;
                if (c2 > 'Z')
                {
                    c2 = 'A';
                    c1++;
                    if (c1 > 'Z')
                    {
                        throw new IndexOutOfRangeException("Next ID bigger than \"ZZZ999\"");
                    }
                }
            }
        }

        var next = new Tuple<char, char, char, int>(c1, c2, c3, number);

        return $"{next.Item1}{next.Item2}{next.Item3}{next.Item4.ToString().PadLeft(3, '0')}";
    }
}
评论
  • nvelit
    nvelit 回复

    无需选择和递增字符串,而是使用SEQUENCE或IDENTITY列生成ID,并且如果需要,可以将其转换为客户端上的字符串。例如

    static string GetId(int id)
    {
        var chars = new char[6];
        char Zero = '0';
        chars[5] = (char) (Zero + id % 10);
        id = id / 10;
        chars[4] = (char)(Zero + id % 10);
        id = id / 10;
        chars[3] = (char)(Zero + id % 10);
        id = id / 10;
        char A = 'A';
        chars[2] = (char)(A + id % 26);
        id = id / 26;
        chars[1] = (char)(A + id % 26);
        id = id / 26;
        chars[0] = (char)(A + id % 26);
    
        return new string(chars);
    }