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

问题描述 投票:0回答:1

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

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

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

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

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

代码概述:

。net核心微服务CQRS亚马逊SQS轨道交通自动贴图MediatR

消费者

    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;

        }
    }

COMMAND

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;
    }
}

HANDLER

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;
        }
    }

HELPER

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')}";
    }
}
c# entity-framework asynchronous .net-core cqrs
1个回答
0
投票

而不是选择和递增字符串,而是使用SEQUENCE或IDENTITY列生成ID,如果需要,则将其转换为客户端上的字符串。 EG

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.