问题描述
我试图将一些键值对缓存到一个并发字典中,以避免每次我需要该值时都去宇宙。这是我的代码。
public class activitylogHubIngress
{
private readonly ICustomerDbService _customerDbService;
private static ConcurrentDictionary<string,string> _customerIdLookup => new ConcurrentDictionary<string,string>(StringComparer.InvariantCultureIgnoreCase);
public activitylogHubIngress(ICustomerDbService customerDbService)
{
_customerDbService = customerDbService;
}
[FunctionName("activitylogHubIngress")]
public async Task Run([EventHubTrigger("activity-log-events",Connection = "activitylogEventHub")] EventData[] events,ILogger log)
{
//Some code removed for brevity. At some point in this Azure Function the following line gets called to retrieve a customer ID.
string customerId = await GetCustomerId(activitylogHubEvent.SubscriptionId,log);
//Some code removed for brevity.
}
private async Task<string> GetCustomerId(string subscriptionId,ILogger log = null)
{
if (_customerIdLookup.TryGetValue(subscriptionId,out string customerId))
{
return customerId;
}
var customer = await _customerDbService.GetCustomerBySubscription(subscriptionId);
if(customer is null)
{
_customerIdLookup.AddOrUpdate(subscriptionId,string.Empty,(key,value) => string.Empty);
if (log != null)
{
log.Loginformation(ApplicationEvents.activitylogUnkNownSubscriptionFailure,$"Added Non-Customer ({subscriptionId}: null) to _customerIdLookup" +
$"\nListing _customerIdLookup dictionary (item count {_customerIdLookup.Count})" +
$"\n{string.Join("\n",_customerIdLookup.Keys.Select(k => $"{k}: {_customerIdLookup[k]}").ToList())}");
}
return null;
}
_customerIdLookup.AddOrUpdate(subscriptionId,customer.Id,value) => customer.Id);
if(log != null)
{
log.Loginformation(ApplicationEvents.activitylogUnkNownSubscriptionFailure,$"Added ({subscriptionId}: {customer.Id}) to _customerIdLookup" +
$"\nListing _customerIdLookup dictionary (item count {_customerIdLookup.Count})" +
$"\n{string.Join("\n",_customerIdLookup.Keys.Select(k => $"{k}: {_customerIdLookup[k]}").ToList())}");
}
return customer.Id;
}
代码执行正常,但意图是返回值
var customer = await _customerDbService.GetCustomerBySubscription(subscriptionId);
将缓存在 _customerIdLookup 中,然后在下一个具有相同订阅 ID 的事件时通过字典访问,而不是转到 cosmos。但是,_customerIdLookup 仍然为空,即使我使用相同的订阅 ID 发送多个事件,代码也始终通过 Cosmos 进行路由。
我所有的日志看起来都像这样。
Added (84b*****-****-****-****-***********0f: 12345678) to _customerIdLookup
Listing _customerIdLookup dictionary (item count 0)
项目计数始终为零。
我做错了什么,字典没有被写入?
解决方法
问题在于你对字典的声明:
private static ConcurrentDictionary<string,string> _customerIdLookup => new ConcurrentDictionary<string,string>(StringComparer.InvariantCultureIgnoreCase);
注意 lambda 符号 =>
,这意味着每次访问成员时都会返回一个新实例。