在ASP.NET WebAPI 中使用緩衝【Redis】

來源:互聯網
上載者:User

標籤:

初步看了下CacheCow與OutputCache,感覺還是CacheOutput比較符合自己的要求,使用也很簡單

PM>Install-Package Strathweb.CacheOutput.WebApi2

基礎使用

CacheOutput特性

        [Route("get")]        [CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]        public IEnumerable<string> Get()        {            return new string[] { "Tom", "Irving" };        }

以參數為key

        [Route("get")]        [CacheOutput(ServerTimeSpan = 50, ExcludeQueryStringFromCacheKey = true)]        public string Get(int id)        {            return DateTime.Now.ToString();        }

Etag頭

使用Redis

用戶端使用StackExchange.Redis,Install-Package StackExchange.Redis

在Autofac中註冊Redis串連

          var builder = new ContainerBuilder();            //註冊api容器的實現            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());            //註冊mvc容器的實現            // builder.RegisterControllers(Assembly.GetExecutingAssembly());            //在Autofac中註冊Redis的串連,並設定為Singleton             builder.Register(r =>            {                return ConnectionMultiplexer.Connect(DBSetting.Redis);            }).AsSelf().SingleInstance();            var container = builder.Build();            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

通過構造注入即可

/// <summary>    ///Redis服務    /// </summary>    public class RedisService : IRedisService    {        private static readonly Logger logger = LogManager.GetCurrentClassLogger();        /// <summary>        ///Redis服務        /// </summary>        private readonly ConnectionMultiplexer _connectionMultiplexer;        /// <summary>        /// 建構函式        /// </summary>        /// <param name="connectionMultiplexer">Redis服務</param>        public RedisService(ConnectionMultiplexer connectionMultiplexer)        {            _connectionMultiplexer = connectionMultiplexer;        }        /// <summary>        /// 根據KEY獲得值        /// </summary>        /// <param name="key">key</param>        /// <returns></returns>        public async Task<WebAPIResponse> Get(string key)        {            try            {                var db = _connectionMultiplexer.GetDatabase();               /*               var set = await db.StringSetAsync("name", "irving");               var get = await db.StringGetAsync("name");               */                return new WebAPIResponse                {                    IsError = false,                    Msg = string.Empty,                    Data = await db.StringGetAsync(key)                };            }            catch (Exception ex)            {                logger.Error(ex, "RedisService Get Exception : " + ex.Message);                return new WebAPIResponse               {                   IsError = false,                   Msg = string.Empty,                   Data = string.Empty               };            }        }    }

CacheOutput與Redis

預設CacheOutput使用System.Runtime.Caching.MemoryCache來快取資料,可以自訂擴充到DB,Memcached,Redis等;只需要實現IApiOutputCache介面

public interface IApiOutputCache{    T Get<T>(string key) where T : class;    object Get(string key);    void Remove(string key);    void RemoveStartsWith(string key);    bool Contains(string key);    void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null);}

實現服務
/// <summary>    /// 實現Redis服務    /// </summary>    public class RedisCacheProvider : IApiOutputCache    {        /// <summary>        ///Redis服務        /// </summary>        private readonly ConnectionMultiplexer _connectionMultiplexer;        /// <summary>        /// 建構函式        /// </summary>        /// <param name="connectionMultiplexer">Redis服務</param>        public RedisCacheProvider(ConnectionMultiplexer connectionMultiplexer)        {            _connectionMultiplexer = connectionMultiplexer;        }        public void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null)        {            throw new NotImplementedException();        }        public IEnumerable<string> AllKeys        {            get { throw new NotImplementedException(); }        }        public bool Contains(string key)        {            throw new NotImplementedException();        }        public object Get(string key)        {            var db = _connectionMultiplexer.GetDatabase();            return db.StringGet(key);        }        public T Get<T>(string key) where T : class        {            throw new NotImplementedException();        }        public void Remove(string key)        {            throw new NotImplementedException();        }        public void RemoveStartsWith(string key)        {            throw new NotImplementedException();        }    }

註冊WebAPIConfig

configuration.CacheOutputConfiguration().RegisterCacheOutputProvider(() => RedisCacheProvider);

或者使用Autofac for Web API

var builder = new ContainerBuilder();builder.RegisterInstance(new RedisCacheProvider());config.DependencyResolver = new AutofacWebApiDependencyResolver(builder.Build());

Refer:
How to use caching in ASP.NET Web API?
http://stackoverflow.com/questions/14811772/how-to-use-caching-in-asp-net-web-api
Output caching in ASP.NET Web API
http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
NuGet Package of the Week: ASP.NET Web API Caching with CacheCow and CacheOutput
http://www.hanselman.com/blog/NuGetPackageOfTheWeekASPNETWebAPICachingWithCacheCowAndCacheOutput.aspx
使用CacheCow和ETag緩衝資源
http://www.cnblogs.com/fzrain/p/3618887.html

在ASP.NET WebAPI 中使用緩衝【Redis】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.