What Are the Patterns and Best Practices for Caching in ASP.NET?

前端 未结 3 1386
花落未央
花落未央 2020-12-23 00:22

We are working on a large legacy application and we\'re redesigning the business layer and the data layer. We believe that it is a good time to redesign the way cache is han

3条回答
  •  甜味超标
    2020-12-23 00:44

    • Just save every queryresult to the database (with cache key: your query, value: your list of business objects)
    • Use distributed cache like memcached next to ASP.Net cache
    • Use a sophisticated cachemanager like https://github.com/enyim/memcached-providers; that can have cache-groups. Some data has to be stored for a long time, some short time. Some data has to be stored in ASP.Net cache, etc.
    • Do calls that has to be stored in the cache using a wrapper function like public T GetFromCache(string key, Func ifKeyNotFoundDelegate) to ensure that cache is always used the same. [1]
    • Think of when to use ASP.Net cache, and when to use distributed cache. Data that is read every request should be stored in ASP.Net, large data like search results; with a lot of different keys and data etc. should be in memcached.
    • Add versioning. Prefix all keys with a versionnumber, so you won't get in trouble when updating your web application, and some objectcontracts change.

    Ah well, that covers most of what we do in our website (20GB memcached cluster spread over 20 servers).

    [1] By making such a function the only interface to store stuff in cache, you can achieve the following. Let's say I want to use something from the cache, like the result from a function. Normally you would do something like

    CacheManager cm = new CacheManager(CacheGroups.Totals);
    object obj = cm.GetFromCache("function1result");
    if(obj == null)
    {
        obj = (object)DAO.Foo();
        cm.StoreInCache("function1result", obj);
    }
    return (List)obj;
    

    By using a different interface you can ensure that users won't make a mistake here.

    Like

    public T GetFromCache(string key, Func ifnotfound)
    {
        T obj = this.GetFromCache(key) as T;
        if(obj == default(T)) 
        { 
             obj = ifnotfound.Invoke();
             this.StoreInCache(key, obj);
        }
        return obj;
    }
    

    This ensures that

    1. We always work with the correct type
    2. That your user always work with cache the same way

    Ergo: less probable that they make a mistake. Furthermore: you get nicer, more clear, code, like:

    List list = new CacheManager(CacheGroups.Total).GetFromCache>("function1result", ()=>DAO.Foo());
    

提交回复
热议问题