在ASP.NET WebAPI 中使用缓存【Redis】

摘要:
初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单PM˃Install-PackageStrathweb.CacheOutput.WebApi2基础使用CacheOutput特性[Route("get")][CacheOutput(ClientTimeSpan=60,ServerTimeSpan=60)]publicIEnumerab

初步看了下CacheCowOutputCache,感觉还是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(intid)
        {
            returnDateTime.Now.ToString();
        }

Etag头

image

使用Redis

客户端使用StackExchange.RedisInstall-Package StackExchange.Redis.StrongName

在Autofac中注册Redis连接

var builder = newContainerBuilder();
            //注册api容器的实现
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //注册mvc容器的实现
            //builder.RegisterControllers(Assembly.GetExecutingAssembly());
            //在Autofac中注册Redis的连接,并设置为Singleton 
            builder.Register(r =>
            {
                returnConnectionMultiplexer.Connect(DBSetting.Redis);
            }).AsSelf().SingleInstance();
            var container =builder.Build();
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

通过构造注入即可

/// <summary>
    ///Redis服务
    /// </summary>
    public classRedisService : IRedisService
    {
        private static readonly Logger logger =LogManager.GetCurrentClassLogger();
        /// <summary>
        ///Redis服务
        /// </summary>
        private readonlyConnectionMultiplexer _connectionMultiplexer;
        /// <summary>
        ///构造函数
        /// </summary>
        /// <param name="connectionMultiplexer">Redis服务</param>
        publicRedisService(ConnectionMultiplexer connectionMultiplexer)
        {
            _connectionMultiplexer =connectionMultiplexer;
        }
        /// <summary>
        ///根据KEY获得值
        /// </summary>
        /// <param name="key">key</param>
        /// <returns></returns>
        public async Task<WebAPIResponse> Get(stringkey)
        {
            try
            {
                var db =_connectionMultiplexer.GetDatabase();
               /*
               var set = await db.StringSetAsync("name", "irving");
               var get = await db.StringGetAsync("name");
               */
                return newWebAPIResponse
                {
                    IsError = false,
                    Msg = string.Empty,
                    Data = awaitdb.StringGetAsync(key)
                };
            }
            catch(Exception ex)
            {
                logger.Error(ex, "RedisService Get Exception : " +ex.Message);
                return newWebAPIResponse
               {
                   IsError = false,
                   Msg = string.Empty,
                   Data = string.Empty
               };
            }
        }
    }
CacheOutput与Redis

默认CacheOutput使用System.Runtime.Caching.MemoryCache来缓存数据,可以自定义扩展到DB,Memcached,Redis等;只需要实现IApiOutputCache接口

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

实现服务

/// <summary>
    ///实现Redis服务
    /// </summary>
    public classRedisCacheProvider : IApiOutputCache
    {
        /// <summary>
        ///Redis服务
        /// </summary>
        private readonlyConnectionMultiplexer _connectionMultiplexer;
        /// <summary>
        ///构造函数
        /// </summary>
        /// <param name="connectionMultiplexer">Redis服务</param>
        publicRedisCacheProvider(ConnectionMultiplexer connectionMultiplexer)
        {
            _connectionMultiplexer =connectionMultiplexer;
        }
        public void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null)
        {
            throw newNotImplementedException();
        }
        public IEnumerable<string>AllKeys
        {
            get { throw newNotImplementedException(); }
        }
        public bool Contains(stringkey)
        {
            throw newNotImplementedException();
        }
        public object Get(stringkey)
        {
            var db =_connectionMultiplexer.GetDatabase();
            returndb.StringGet(key);
        }
        public T Get<T>(string key) where T : class
        {
            throw newNotImplementedException();
        }
        public void Remove(stringkey)
        {
            throw newNotImplementedException();
        }
        public void RemoveStartsWith(stringkey)
        {
            throw newNotImplementedException();
        }
    }

注册WebAPIConfig

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

或者使用Autofac for Web API

var builder = newContainerBuilder();
builder.RegisterInstance(newRedisCacheProvider());
config.DependencyResolver = new AutofacWebApiDependencyResolver(builder.Build());

REFER:
Lap around Azure Redis Cache
http://azure.microsoft.com/blog/2014/06/04/lap-around-azure-redis-cache-preview/
Caching data in Azure Redis Cache
https://msdn.microsoft.com/en-us/library/azure/dn690521.aspx
ASP.NET Output Cache Provider for Azure Redis Cache
https://msdn.microsoft.com/en-us/library/azure/dn798898.aspx
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 - Use Redis as CacheManager
http://www.codeproject.com/Tips/825904/ASP-NET-WebApi-Use-Redis-as-CacheManager
RedisReact
https://github.com/ServiceStackApps/RedisReact
.Net缓存管理框架CacheManager
http://www.cnblogs.com/JustRun1983/p/CacheManager.html

免责声明:文章转载自《在ASP.NET WebAPI 中使用缓存【Redis】》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇四种程序启动画面的制作方法(VC)MAPGIS把经纬度坐标转换为大地坐标下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

缓存子系统如何设计

缓存子系统如何设计 大家对这段代码肯定很熟悉吧: public List<UserInfo> SearchUsers(stringuserName) { string cacheKey=string.Format("SearchUsers_{0}", userName);...

JQuery EasyUI datagrid 批量编辑和提交

前台主要代码: <script type="text/javascript"> $(function() { var $dg = $("#dg"); $dg.datagrid({ url : "servlet/list", width : 700,...

解析数据库连接字符串 (将Data Source、Initial Catalog、User ID、Password取出)

private void AnalysisConnectionstring() { string tempStr = “Data Source=192.168.2.123;Initial Catalog=caxastat;Persist Security Info=True;User ID=sa;Passwor...

ngx_lua应用最佳实践

引子: 以下文字,是UPYUN系统开发工程师timebug在SegmentFault D-Day南京站技术沙龙上所做分享的内容要义提炼,主题为UPYUN系统开发团队在进行业务逻辑由C模块到ngx_lua的迁移过程中产生的心得体会,以及在NGINX上基于ngx_lua的方面的最佳实践方案。 Upyun公众号:upaiyun -----------------...

Linux下常用redis指令

set get 取值赋值,key值区分大小写 mset mget多个的取值和赋值 del 删除一个或多个key 查看key值是否存在,有就返回1,没有就是0 设置一个有存活时间的key值,设置成功返回1 显示key值剩余存活时间 keys显示符合指定条件的key 创建相关数据类型,并使用keys显示对应的数据类型 创建hash类型的数据...

&amp;lt;转&amp;gt;PHP中正则表达式函数

PHP中的正则表达式函数       在PHP中有两套正则表达式函数库。一套是由PCRE(Perl Compatible Regular Expression)库提供的,基于传统型NFA。PCRE库使用和Perl相同的语法规则实现了正则表达式的模式匹配,其使用以“preg_”为前缀命名的函数。另一套是由POSIX(Portable Operation Sy...