在ASP.NET WebAPI 中使用缓存【Redis】
初步看了下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.StrongName
在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:
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
相关文章
- 《Netty Zookeeper Redis 高并发实战》 图书简介
- .net core 使用Redis的发布订阅
- 中小研发团队架构实践之生产环境诊断工具WinDbg 三分钟学会.NET微服务之Polly 使用.Net Core+IView+Vue集成上传图片功能 Fiddler原理~知多少? ABP框架(asp.net core 2.X+Vue)模板项目学习之路(一) C#程序中设置全局代理(Global Proxy) WCF 4.0 使用说明 如何在IIS上发布,并能正常访问
- MVC的验证(模型注解和非侵入式脚本的结合使用) .Net中初探Redis .net通过代码发送邮件 Log4net (Log for .net) 使用GDI技术创建ASP.NET验证码 Razor模板引擎 (RazorEngine) .Net程序员应该掌握的正则表达式
- Codis作者黄东旭:细说分布式Redis架构设计和那些踩过的坑
- Redis开发与运维. 导读
- nginx+tomcat+redis负载均衡,实现session共享
- 详解 Redis 应用场景及应用实例
- .NET中使用Redis
- Redis的GEO
- redis编译安装部署--redis-5.0.3
- Redis主从节点和哨兵的部署
- redis Key相关命令
- 【转】Java十大常用框架介绍(spring系+dubbo+RabbitMQ+Ehcache+redis)
- Redis 性能測试
- 你真的懂redis的数据结构了吗?redis内部数据结构和外部数据结构揭秘
- Redis学习系列二之.Net开发环境搭建及基础数据结构String字符串
- redis的主从复制,读写分离,主从切换
- Redis 发布订阅