![](/img/trans.png)
[英]Sharing variables across ASP.NET Core controllers and first initialization
[英]Sharing a list between controllers safely in ASP.NET Core
我正在使用 ASP.NET Core 3.1。 我正在編寫一個控制器來處理 webhooks,並且發送請求的系統可能會多次發送相同的請求。 每個請求都有一個通知 ID 標頭,對於重復的請求將相同,因此很容易將它們過濾掉。
在正確線程安全的 ASP.NET Core 中處理此問題的最佳方法是什么? 現在我在MemoryCache
存儲一個List<string>
,它可以工作,但我擔心線程安全。 我不知道提供類似.Contains()
類的線程安全列表的集合來快速檢查集合中是否存在某些內容。
處理這種情況的最佳方法是什么?
我建議只使用Asp.Net Core IMemoryCache 。 沒有集合對象。
這樣你就可以對緩存對象的生命周期進行一些控制。 例如,您可以只保留一小時。
[ApiController]
public class HomeController : Controller
{
private readonly IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
public ActionResult Get(string notificationId)
{
if (_cache.TryGetValue(notificationId, out _))
return Ok();
// Do stuff
// Store key for one hour
_cache.Set(notificationId, notificationId, TimeSpan.FromHours(1));
return Ok();
}
}
警告!
如果您只有一個 webhook 實例並且您不打算對其進行水平擴展,則這種方法是有意義的。
或者,如果您對每個實例都有自己的緩存並可能為每個實例處理一次相同的請求感到滿意。
否則,需要分布式緩存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.