Ben*_*ell 5 .net c# redis stackexchange.redis
我在集群 ASP.Net Core 服务器上使用 Stackexchange.Redis,但在处理事务时遇到了一些麻烦。
以下代码应该从两个散列“HashA”和“HashB”中删除键为“hashItemID”的字段,但前提是它同时存在于两个散列中:
var hashAKey = "HashA";
var hashBKey = "HashB";
var id = "hashItemID";
var tran = redis.Database.CreateTransaction();
// Only delete the item if it exists in both hashes
var hashBCondition = tran.AddCondition(Condition.HashExists(hashBKey, id));
var hashACondition = tran.AddCondition(Condition.HashExists(hashAKey, id));
tran.HashDeleteAsync(hashBKey, id);
tran.HashDeleteAsync(hashAKey, id);
var deleted = await tran.ExecuteAsync();
if (!deleted)
{
logger.LogWarning("Failed to delete '{ID}'. HashAResult: {A}, HashBResult: {B}", id, hashACondition.WasSatisfied, hashBCondition.WasSatisfied);
}
Run Code Online (Sandbox Code Playgroud)
有时,此代码会失败并显示日志:
Failed to delete 'hashItemID'. HashAResult: True, HashBResult: True
Run Code Online (Sandbox Code Playgroud)
我的印象是交易只有在不满足条件的情况下才会失败,这是真的吗?
查看网络和性能指标,没有可能导致此问题的超时或高内存使用率。
小智 -1
由于声誉限制,我无法添加评论,您可以尝试以下方法,看看它是否适合您:
var hashAKey = "HashA";
var hashBKey = "HashB";
var id = "hashItemID";
var tran = redis.Database.CreateTransaction();
// Only delete the item if it exists in both hashes
var hashBCondition = tran.AddCondition(Condition.HashExists(hashBKey, id));
var hashACondition = tran.AddCondition(Condition.HashExists(hashAKey, id));
tran.HashDeleteAsync(hashBKey, id);
tran.HashDeleteAsync(hashAKey, id);
bool deleted = await tran.ExecuteAsync();
if (!deleted)
{
logger.LogWarning("Failed to delete '{ID}'. HashAResult: {A}, HashBResult: {B}", id, hashACondition.WasSatisfied, hashBCondition.WasSatisfied);
}
Run Code Online (Sandbox Code Playgroud)
使用bool dead代替 vardeleted