简体   繁体   English

使用Dot Net核心实现缓存管理器

[英]Implementing Cache manager using Dot Net core

I am new to DotNet Core. 我是DotNet Core的新手。 I have created a WEB API using .NEt Core. 我已经使用.NEt Core创建了一个WEB API。 I have a requirement to implement cache manager in this API. 我需要在此API中实现缓存管理器。 I have a set of record which will get updated once in a day, so i wanted this data stored in an object in memory and call database only if a change has been detected(or at a definite interval, say 3 hrs). 我有一组记录,每天将更新一次,因此,我希望将此数据存储在内存中的对象中,并仅在检测到更改时(或以一定的时间间隔,例如3个小时)调用数据库。 I already tried implementing a logic in my app. 我已经尝试在我的应用程序中实现逻辑。 but wanted to see if we have a specific packages already available ! 但想看看我们是否已有特定的软件包!

Please help me. 请帮我。

Thanks in advance. 提前致谢。

Asp.Net has a built-in cache libraries that you can use. Asp.Net具有可以使用的内置缓存库。 They are available in .Net core as well, eg you can read about therm here . 它们在.Net core中也可用,例如,您可以在此处阅读有关therm的信息 It's a bit too long to describe here, but generally you need to register it in you services: 这里描述的时间有点太长,但是通常您需要在服务中注册它:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
    }
}

Then you can inject IMemoryCache in your services. 然后,您可以在服务中注入IMemoryCache It requires NuGet package Microsoft.Extensions.Caching.Memory . 它需要NuGet包Microsoft.Extensions.Caching.Memory

You can use asp.net cache which is available in icrosoft.Extensions.Caching.Memory Nuget Package.Install this package if not available. 您可以使用icrosoft.Extensions.Caching.Memory Nuget软件包中可用的asp.net缓存。如果不可用,请安装此软件包。

Then you need to register cache memory service 然后您需要注册缓存服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}

Consume your cache service into controller 将缓存服务消耗到控制器中

 public class CacheController : Controller { private readonly IMemoryCache _cache; public TokenController(IMemoryCache cache) { _config = config; } } 

Use below function to get or set cache data 使用以下功能获取或设置缓存数据

public T GetOrSet<T>(string cacheKey, Func<T> getItemCallBack)
        {
            var item = _cache.Get<T>(cacheKey);
            if (item == null)
            {
                item = getItemCallBack();
                _cache.Set(cacheKey, item, CacheKeysWithOption.CacheOption);
            }
            return item;
        }

consume GetOrSet 消耗GetOrSet

 public IActionResult CacheTryGetValueSet()
    {
        var list = GetOrSet(CacheKeysWithOption.Entry, GetStringList);
        return new JsonResult(list);
    }

    [NonAction]
    public List<String> GetStringList()
    {
        List<String> str = new List<string>()
        {
            "aaaaa",
            "sssdasdas",
            "dasdasdas"
        };
        return str;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM