我有一系列需要并行处理的客户。客户从商店购买产品,我必须确保:
我希望这是高度并发的,因此我想使我的解决方案可交换,并使用commute
而不是alter
并重试,导致写入重试。我只想在缺货时重试客户处理。因此,我选择将每个库存项目都设为ref
。然后,我将使用validator
来确保每个库存商品都不会低于零。例如:
库存商品:
(def stock-item (ref 10))
验证者:
(defn valid-stock-balance? [stock-bal]
(>= stock-bal 0))
设置引用的验证器:
(set-validator! stock-item valid-stock-balance?)
然后在交易中,我将尝试commute
进行如下库存:
(defn- buy-product [amount customer]
(try
(commute stock-item - amount)
(catch Exception e (process-customer customer))))
流程客户看起来像这样:
第3步使用:buy-product
(defn- process-customer [customer]
(dosync
"Process `customer`. Consists of three steps:
1. Finding all stores in which the requested products are still available.
2. Sorting the found stores to find the cheapest (for the sum of all products).
3. Buying the products by updating the `stock`
))
问题
try catch
中使用的buy-product
是否有副作用,不应在process-customer
中的事务中使用?process-customer
内部调用buy-product
的目的是什么?它仅仅是导致嵌套事务还是爆炸?