gpt4 book ai didi

C# 从 mysql 数据库获取代码关键部分的锁

转载 作者:行者123 更新时间:2023-11-29 01:50:03 25 4
gpt4 key购买 nike

我正在使用带有 MySql 数据库的 Asp.NET。

申请流程:

  1. 在 Woocommerce 中创建订单并发送到我的应用
  2. 我的应用程序将 woo 订单对象转换为要添加到外部 ERP 系统的对象
  3. 在外部 ERP 系统中创建的订单,我们使用该订单信息更新本地数据库以了解创建成功

我有一个代码的关键部分,用于在外部 ERP 资源上创建订单。同一订单的多个请求可以同时运行,因为它们是从我无法控制的外部应用程序 (woocommerce) 创建的。因此代码的关键部分必须一次只能允许其中一个请求进入,否则会创建重复的订单。

重要说明:该应用程序托管在具有负载均衡器的 Elastic Beanstalk 上,因此该应用程序可以跨多个服务器进行扩展,这使得标准 C# 锁定对象不起作用。

我想创建一个可以在多个服务器/应用程序实例之间共享的锁,以便一次只有一个服务器可以获得锁并进入代码的关键部分。我找不到如何使用 MySql 和 C# 执行此操作,所以如果有人有一个很好的示例。

下面是我如何进行单实例线程安全锁定。我如何将其转换为跨多个实例安全:

SalesOrder newOrder = new SalesOrder();         //the external order object
var databaseOrder = new SalesOrderEntity(); //local MySql database object

/*
* Make this section thread safe so multiple threads can't try to create
* orders at the same time
*/
lock (orderLock)
{
//check if the order is already locked or created.
//wooOrder comes from external order creation application (WooCommerce)
databaseOrder = GetSalesOrderMySqlDatabase(wooOrder.id.ToString(), originStore);

if (databaseOrder.OrderNbr != null)
{
//the order is already created externally because it has an order number
return 1;
}
if (databaseOrder.Locked)
{
//the order is currently locked and being created
return 2;
}

//the order is not locked so lock it before we attempt to create externally
databaseOrder.Locked = true;
UpdateSalesOrderDatabase(databaseOrder);

//Create a sales order in external system with the specified values
newOrder = (SalesOrder) client.Put(orderToBeCreated);


//Update the order in our own database so we know it's created in external ERP system
UpdateExternalSalesOrderToDatabase(newOrder);

}

如果需要更多详细信息,请告诉我。

最佳答案

为此,您可以使用 MySQL 的命名咨询锁函数 GET_LOCK(name)

这在事务范围之外工作,因此您可以在释放锁之前提交或回滚数据库更改。在这里阅读更多相关信息:https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock

您还可以使用其他一些专用的锁定服务。例如,您可以使用共享消息队列服务来做到这一点。参见 https://softwareengineering.stackexchange.com/questions/127065/looking-for-a-distributed-locking-pattern

关于C# 从 mysql 数据库获取代码关键部分的锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com