亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ASP.NET Core 中的持久內存并發字典

ASP.NET Core 中的持久內存并發字典

C#
達令說 2022-12-24 12:27:31
在 ASP.NET Core 應用程序中,我希望擁有類似于以下內容的持久共享狀態:ConcurrentDictionary<string, Job> Jobs;應用程序的各種組件將訪問此共享狀態(請求處理控制器、后臺任務),但我主要關心的不是并發訪問。我很好奇的是,是否有一種方法可以在我的 ASP.NET Core 應用程序的整個生命周期中保留這樣的全局變量。有沒有我可以定義這個全局Jobs變量的地方,它不會被 ASP.NET Core 運行時破壞?也許MemoryCache以某種方式利用?使用 Redis 之類的東西當然可以,但我很好奇 ASP.NET Core 中是否有針對全局共享狀態的強大的內存中/進程中解決方案。
查看完整描述

3 回答

?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

您可以包裝ConcurrentDictionary在一個類中并將其注冊為單例。


public class SharedJobs

{

    private readonly ConcurrentDictionary<string, Job> _jobs

        = new ConcurrentDictionary<string, Job>();


    public ConcurrentDictionary<string, Job> Jobs => _jobs;

}

在 Startup.cs 中


services.AddSingleton<SharedJobs>();

用法


public class Service

{

    private readonly SharedJobs _shared;


    public Service(SharedJobs shared) => _shared = shared;


    public void DoSomething()

    {

        var job = _shared.Jobs.GetOrAdd("Key", new Job("New Job when not found"));

    }

}

您可以更進一步,隱藏您在幕后使用的事實,ConcurrentDictionary只向消費者公開所需的功能。


public class SharedJobs

{

    private readonly ConcurrentDictionary<string, Job> _jobs

        = new ConcurrentDictionary<string, Job>();


    public Job Get(string key)

    {

        return _jobs.GetOrAdd(key, CreateNewJob());

    }


    private Job CreateNewJob() {}

}


查看完整回答
反對 回復 2022-12-24
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

IMemoryCache在您的控制器/服務的構造函數中請求一個。


首先添加到您的啟動以注冊緩存服務:


public void ConfigureServices(IServiceCollection services)

{

    services.AddMemoryCache();


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

}

...在構造函數中請求它...


private IMemoryCache _cache;


public HomeController(IMemoryCache memoryCache)

{

    _cache = memoryCache;

}

...并使用它...


public IActionResult CacheTryGetValueSet()

{

    DateTime cacheEntry;


    // Look for cache key.

    if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry))

    {

        // Key not in cache, so get data.

        cacheEntry = DateTime.Now;


        // Set cache options.

        var cacheEntryOptions = new MemoryCacheEntryOptions()

            // Keep in cache for this time, reset time if accessed.

            .SetSlidingExpiration(TimeSpan.FromSeconds(3));


        // Save data in cache.

        _cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions);

    }


    return View("Cache", cacheEntry);

}

閱讀 Microsoft 的ASP.NET Core 內存中緩存了解更多詳細信息。以上所有代碼均來自該頁面。


這里提供的內存緩存是一個單例——緩存的單個實例將在應用程序的整個持續時間內存在。但請注意,一旦進程關閉,所有內容都會被清除。


至于“好吧,如果我的緩存在我要求的那一刻沒有價值怎么辦?”


呃,歡迎使用多線程代碼。這只是生活中的事實,緩存未命中是一回事。它將變得“更”可靠,因為整個循環都在內存中,但您仍然需要考慮到這一點。


查看完整回答
反對 回復 2022-12-24
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

IMemoryCache您可以使用AcroFS微型庫在其之上使用持久層。它將首先嘗試從內存加載數據,然后嘗試從磁盤加載數據。


如果您在不同位置有多個項目,您可以為緩存文件夾設置一個絕對路徑。


// set cache

_memoryCache.Persistent().Set(key, jobs);


// get cache

var found = _memoryCache.Persistent().TryGetValue(cacheKey, out jobs);


// get or create

var jobs = await _memoryCache.Persistent().GetOrCreate(cacheKey, async entry => await loadJobsAsync());


查看完整回答
反對 回復 2022-12-24
  • 3 回答
  • 0 關注
  • 208 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號