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

初步看了下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(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
版权声明:本文为作者原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/admans/p/11288353.html

时间: 2024-08-08 01:28:06

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

在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() { retu

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

.NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对Redis和SQL Server的原生支持.除了这个独立的缓存系统之外,ASP.NET Core还借助一个中间件实现了“响应缓存”,它会按照HTTP缓存规范对整个响应实施缓存.不过按照惯例,在对缓存进行系统介绍之前,我们还是先通过一些简单的实例演示感知一下如果在一个ASP.NET Core应用中如何

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

1. /// <summary> /// 获取上下文中的cookie /// </summary> /// <returns></returns> [HttpGet] [HttpPost] public string GetOne() { //1.在WebApi中这种方式获取cookie 可以成功 //2.在WebApi 中这种凡是获取Form,QueryString 中的参数是有效的 HttpCookieCollection collection= Htt

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

一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAPI中就是一个MessageHandle,具体请查找关键字“ASP.NET Forms” How:如何启动Forms认证? 最简单的是通过配置启动Forms认证: 1 <system.web> 2 <authentication mode="Forms"> 3 <

Asp.Net WebAPI中Filter过滤器的使用以及执行顺序

转发自:http://www.cnblogs.com/UliiAn/p/5402146.html 在WEB Api中,引入了面向切面编程(AOP)的思想,在某些特定的位置可以插入特定的Filter进行过程拦截处理.引入了这一机制可以更好地践行DRY(Don’t Repeat Yourself)思想,通过Filter能统一地对一些通用逻辑进行处理,如:权限校验.参数加解密.参数校验等方面我们都可以利用这一特性进行统一处理,今天我们来介绍Filter的开发.使用以及讨论他们的执行顺序. Filter

动态类型和匿名类型在asp.net webapi中的应用

1.  动态类型用于webapi调用 假设需要调用一个webapi,webapi返回了一个json字符串.字符串如下: {"ProductId":"AN002501","ProductName":"XX洗衣粉","Description":"","UnitPrice":9.9} 问:如何获得json字符串中的值? 常规的做法是:先构建一个类,然后再使用JsonConv

ASP.NET WebAPI 08 Message,HttpConfiguration,DependencyResolver

Message WebAPI作为通信架构必定包含包含请求与响应两个方法上的报文,在WebAPI它们分别是HttpRequestMessage,HttpResponseMessage.对于HttpResponseMessage之前在WebAPI返回结果中有应用. HttpRequestMessage 请求报文包含请求地址(RequestUri),请求方法(Method),头信息(Headers),报文信息(Content)以及Http版本(Versions) public class HttpRe

Asp.Net MVC 中实现跨域访问

在ASP.Net webapi中可以使用  Microsoft.AspNet.WebApi.Cors  来实现: public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: &

ASP.NET WebApi+Vue前后端分离之允许启用跨域请求

前言: 这段时间接手了一个新需求,将一个ASP.NET MVC项目改成前后端分离项目.前端使用Vue,后端则是使用ASP.NET WebApi.在搭建完成前后端框架后,进行接口测试时发现了一个前后端分离普遍存在的问题跨域(CORS)请求问题.因此就有了这篇文章如何启用ASP.NET WebApi 中的 CORS 支持. 一.解决Vue报错:OPTIONS 405 Method Not Allowed问题: 错误重现: index.umd.min.js:1 OPTIONS http://local