初步看了下CacheCowOutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单

PM>Install-Package Strathweb.CacheOutput.WebApi2

基础使用

CacheOutput特性

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

以参数为key

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

Etag头

使用Redis

客户端使用StackExchange.RedisInstall-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

---------------------
作者:Irving
来源:CNBLOGS
原文:https://www.cnblogs.com/Irving/p/4618556.html
版权声明:本文为作者原创文章,转载请附上博文链接!

[转]在ASP.NET WebAPI 中使用缓存【Redis】的更多相关文章

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

    初步看了下CacheCow与OutputCache,感觉还是CacheOutput比较符合自己的要求,使用也很简单 PM>Install-Package Strathweb.CacheOutpu ...

  2. 关于ASP.NET WebAPI中HTTP模型的相关思考

    对于.NET的分布式应用开发,可以供我们选择的技术和框架比较多,例如webservice,.net remoting,MSMQ,WCF等等技术.对于这些技术很多人都不会陌生,即时没有深入的了解,但是肯 ...

  3. asp.net mvc5中使用缓存依赖SqlCacheDependency

    缓存是用来提高应用性能,降低服务器压力.适用于数据不易变,数据易通用的情景, 对于动态查询数据,例如数据分析,最好放弃使用缓存.使用缓存最麻烦的就是保持源数据和缓存的中的数据一致. 缓存(Cache) ...

  4. ASP.Net Core使用分布式缓存Redis从入门到实战演练

    一.课程介绍 人生苦短,我用.NET Core!缓存在很多情况下需要用到,合理利用缓存可以一方面可以提高程序的响应速度,同时可以减少对特定资源访问的压力.  所以经常要用到且不会频繁改变且被用户共享的 ...

  5. 在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

    一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAP ...

  6. Asp.Net WebAPI 中Cookie 获取操作方式

    1. /// <summary> /// 获取上下文中的cookie /// </summary> /// <returns></returns> [H ...

  7. ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存

    .NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对 ...

  8. [翻译] ASP.NET WebAPI 中的异常处理

    原文链接:https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling 本文介绍 ...

  9. ASP.NET Core 中的缓存

    目录 缓存的基本概念 缓存原理 缓存设计 分布式缓存 Memcache 与 Redis 的比较 缓存穿透,缓存击穿,缓存雪崩解决方案 数据一致性 使用内置 MemoryCache 使用分布式缓存 Re ...

随机推荐

  1. [Vue CLI 3] Uglify 相关的应用和设计

    在本文开始之前,先留一个问题? 如果在新版本我想加一个 drop_console 的配置呢? 在老版本的脚手架生成的配置中,对于线上环境的文件:webpack.prod.conf.js 使用了插件:u ...

  2. HTML5小知识汇总

    1.关于<!DOCTYPE HTML> H5只需要<!DOCTYPE HTML>这样简单的声明,不用之前一长串代码,因为H5不是基于SGML,所以不需要对DTD引用,但是需要D ...

  3. 【转载】【技巧总结】PyCharm怎么克隆github上开源的项目

    PyCharm怎么clone github上开源的项目 一.先要确保PyCharm正确的配置了Git   如果你已经在PyCharm中配置好了Git,可以跳过此步骤,直接看下一步.   那么怎么在Py ...

  4. Spring_通过Bean的Factory配置Bean

    package com.tanlei.bean.FactoryBean; import org.springframework.beans.factory.FactoryBean; public cl ...

  5. 【JZOJ4814】【NOIP2016提高A组五校联考2】tree

    题目描述 给一棵n 个结点的有根树,结点由1 到n 标号,根结点的标号为1.每个结点上有一个物品,第i 个结点上的物品价值为vi. 你需要从所有结点中选出若干个结点,使得对于任意一个被选中的结点,其到 ...

  6. JS对HTML实体字符转义和反转义

    一.名词解释 HTML实体字符: 由于在HTML中有些符号是预留的,比如在html中不能直接使用尖括号(‘<’或‘>’),会被误认为标签符号.所以需要通过HTML实体字符去进行替换: HT ...

  7. Directx11教程(5) 画一个简单的三角形(1)

    原文:Directx11教程(5) 画一个简单的三角形(1)       在本篇教程中,我们将通过D3D11画一个简单的三角形.在D3D11中,GPU的渲染主要通过shader来操作(当然还有一些操作 ...

  8. oracle-Restrict权限

    启动数据库并把它置于open模式,直给拥有restricted session权限的用户赋予访问权. Alter system disable restricted session; 另外,启动时,o ...

  9. 模拟登录新浪微博(Python) - 转

    Update: 如果只是写个小爬虫,访问需要登录的页面,采用填入cookie 的方法吧,简单粗暴有效,详细见:http://www.douban.com/note/264976536/模拟登陆有时需要 ...

  10. closest和parents方法区别

    今天第一次看到closest方法,以前也从来没用过. 该方法从元素本身开始往上查找,返回最近的匹配的祖先元素. 1.closest查找开始于自身,parents开始于元素父级 2.closest向上查 ...