具有多个微服务实例的重复数据

时间:2018-11-06 15:39:50

标签: c# entity-framework asp.net-core-2.0 microservices

我对重复数据有疑问。 我有一个客户端,多次调用API来填充一些网格。 API实例是一种检查数据是否存在以及是否创建所有数据的服务。 问题是,当创建数据的方法很繁重并且需要很长时间时。因此,两种方法可以同时运行,并且两种方法都可以保存数据并创建重复数据 我可以将API调用排入队列,然后一次将其排除吗? 还是有另一种方法可以实现? 这里的API代码

[Produces("application/json")]
[Route("api/v1/Combinations")]
public class CombinationsController : Controller
{
    private readonly ICommonService _CommonService;
    private readonly ILogger _logger;

    public CombinationsController(ICommonService CommonService,
        ILogger<CombinationsController> logger)
    {
        _logger = logger;
        _CommonService = CommonService;
    } 

    [HttpPost("GenerateCombinationsByAttributes",Name ="GenerateCombinationsByAttributes")]
    public async Task<IActionResult> GenerateCombinationsByAttributes([FromBody] List<Guid> attributeIds)
    {
        if (attributeIds == null || attributeIds.Count == 0 || attributeIds.Contains(Guid.Empty))
            return BadRequest();

        var ret = await _CommonService.GenerateCombinationByAttributesList(attributeIds);

        return Ok();
    }

}

1 个答案:

答案 0 :(得分:0)

我想我已经用一个简单的信号量来解决了这个问题 我已经声明了

static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);

在微服务类内部 然后

 public async Task<Result> GenerateCombinationByAttributesList(List<Guid> attributeIds)
    {
        var result = new Result();
        await semaphoreSlim.WaitAsync();
        try
        {
            DoHeavyStuffHere();

        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            result.SetError(ex.Message);
        }
        finally
        {
            semaphoreSlim.Release();
        }
        return result;
    }
相关问题