简体   繁体   English

如何在自托管的WebAPI应用程序中正确缓存数据

[英]how to properly cache data in a self-hosted WebAPI application

I have a C# WebAPI application, self-hosted with TopShelf. 我有一个C#WebAPI应用程序,由TopShelf自行托管。 I need to optimize some of my data access by querying a few databases upon application start-up, and then caching the results (which are static) for any subsequent access by my WebAPI controllers. 我需要通过在应用程序启动时查询一些数据库来优化我的某些数据访问,然后将结果(静态)缓存到WebAPI控制器的任何后续访问中。 My solution consists of two projects: 我的解决方案包含两个项目:

ServiceHub.Topshelf.WebAPI (which contains all business logic) and Topshelf.WebPI (whic only hosts WebApiConfigurator.cs) ServiceHub.Topshelf.WebAPI(包含所有业务逻辑)和Topshelf.WebPI(仅承载WebApiConfigurator.cs)

What is the proper technique for doing this type of data caching? 进行此类数据缓存的正确技术是什么?

As Ric suggested, I've looked at the Cache class. 正如Ric所建议的那样,我研究了Cache类。 Here is what I did in my SIgnedContractsController.csc to accomplish the caching: 这是我在SIgnedContractsController.csc中完成缓存的操作:

using System.Runtime.Caching;
.....
ObjectCache cache;
List<Model.SignedContracts> allSignedContracts;
.....

cache = MemoryCache.Default;
            allSignedContracts = cache["signed_contracts"] as List<Model.SignedContracts>;

            if (allSignedContracts == null)
            {
                allSignedContracts = new List<Model.SignedContracts>();
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1.0);
                var result = (from contracts in new XPQuery<Model.SignedContracts>(uow) select contracts);
                foreach (var item in result)
                {
                    allSignedContracts.Add(item); 
                }
                cache.Add("signed_contracts",allSignedContracts,policy);

            }

Then, in the GET method I did this: 然后,在GET方法中,我这样做:

public HttpResponseMessage Get()
        {

            var _americasPriorWeekThree = Convert.ToInt32((from contracts in allSignedContracts
                                                           where contracts.Region == "Americas"
                                                       select contracts.PriorWeek3).First());

....... .......

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

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