65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Redis 在 Windows 上实现支持云的本地缓存解决方案

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2016年4月23日

CPOL

3分钟阅读

viewsIcon

27384

本文描述了如何使用 .NET 平台上的 Redis 编写缓存解决方案。

引言

在开发应用程序时,缓存通常在提高应用程序性能和实现一些关键功能方面发挥着重要作用。

本文将介绍如何使用 Microsoft Visual Studio 和 C# 语言,在 Windows 上使用 Redis 来干净利落地解决这个问题。StackExchange Redis 是市面上最好的 .NET Redis 客户端之一,本文将使用它。

该代码也可以直接用于 Azure 云上的 Redis 缓存。

解决方案步骤

以下是将 Redis 缓存包含到您的解决方案中所需的步骤

  1. 使用此 MSOpenTech 页面上提供的任何版本来安装适用于 Windows 的 Redis。此解决方案已在版本 2.8.2104、2.8.2400 和 3.0.501 上进行了测试。
  2. 安装完成后,您的 Windows 计算机的服务控制台中应该有一个 Redis 服务。请确保该服务正在运行。
  3. 使用 Microsoft Visual Studio 创建一个新的 .NET 解决方案。
  4. 使用程序包管理器或以下命令将 StackExchange.Redis 客户端和另外两个 NuGet 程序包添加到解决方案中
    PM> Install-Package StackExchange.Redis
    PM> Install-Package StackExchange.Redis.Extensions.Core
    PM> Install-Package StackExchange.Redis.Extensions.Newtonsoft

    这将为您的项目添加对 StackExchange.Redis 库的引用。

    注意:如果您的解决方案需要强命名,请使用 StackExchange.Redis.StrongName

  5. 将 Redis 连接字符串添加到您的 App.Config(如果是 Web 应用程序,则为 Web.Config)。一个简单的连接字符串看起来会像这样
      <connectionStrings>
        <clear />
        <add name="RedisCacheConnection" connectionString="localhost:6379,ssl=false" />
      </connectionStrings>
  6. 将以下键添加到 Config 文件中,以显式选择特定的 Redis 数据库。单个 Redis 实例默认有 16 个数据库/分区(0 到 15)。
      <appSettings>
        <add key="RedisDatabaseNumber" value="1" />
        <add key="RedisCacheExpiration" value="20" />
      </appSettings>
  7. 添加对 System.Configuration 库的引用。
  8. 创建一个新类,该类将连接到 Redis 客户端,类似于以下类
    using StackExchange.Redis.Extensions.Core;
    using StackExchange.Redis.Extensions.Newtonsoft;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    
    namespace RedisDemo
    {
        public class RedisClient<T>
        {
            /// <summary>
            /// Connection string to the redis cache instance
            /// </summary>
            protected string cacheConnectionString;
    
            /// <summary>
            /// Cache object expiration time
            /// </summary>
            protected int cacheObjectExpiration;
    
            /// <summary>
            /// Redis DB instance to be used
            /// </summary>
            protected short redisDb;
    
            /// <summary>
            /// Default constructor
            /// </summary>
            public RedisClient()
            {
                cacheConnectionString = ConfigurationManager.ConnectionStrings
                                        ["RedisCacheConnection"].ConnectionString;
                redisDb = Convert.ToInt16(ConfigurationManager.AppSettings["RedisDatabaseNumber"]);
                cacheObjectExpiration = Convert.ToInt32
                        (ConfigurationManager.AppSettings["RedisCacheExpiration"]);
            }
    
            /// <summary>
            /// Initializes and returns Redis cache client
            /// </summary>
            /// <returns>Redis Cache client</returns>
            protected StackExchangeRedisCacheClient GetCacheClient()
            {
                var serializer = new NewtonsoftSerializer();
                var cacheClient = new StackExchangeRedisCacheClient
                                     (serializer, cacheConnectionString, redisDb);
                return cacheClient;
            }
    
            /// <summary>
            /// Flushes the cache
            /// </summary>
            public void FlushCache()
            {
                using (var cacheClient = this.GetCacheClient())
                {
                    cacheClient.FlushDb();
                }
            }
    
            /// <summary>
            /// Add the item to the cache
            /// </summary>
            /// <param name="key"></param>
            /// <param name="cacheObject"></param>
            public void AddToCache(string key, T cacheObject)
            {
                using (var cacheClient = GetCacheClient())
                {
                    if (cacheClient.Exists(key))
                    {
                        cacheClient.Replace
                           (key, cacheObject, new TimeSpan(0, cacheObjectExpiration, 0));
                    }
                    else
                    {
                        cacheClient.Add(key, cacheObject, new TimeSpan(0, cacheObjectExpiration, 0));
                    }
                }
            }
    
            /// <summary>
            /// Retrieve an item from cache based on the key
            /// </summary>
            /// <param name="key"></param>
            /// <returns></returns>
            public T GetCachedItem(string key)
            {
                using (var cacheClient = this.GetCacheClient())
                {
                    var cachedObject = cacheClient.Get<T>(key);
                    return cachedObject;
                }
            }
    
            /// <summary>
            /// Get all the items cached
            /// </summary>
            /// <returns></returns>
            public IEnumerable<T> GetAllCachedItems()
            {
                using (var cacheClient = GetCacheClient())
                {
                    var keys = cacheClient.SearchKeys("*");
                    var dictCollection = cacheClient.GetAll<T>(keys);
                    return dictCollection.Values.ToList();
                }
            }
        }
    }
  9. 缓存客户端类已准备好使用。您现在可以实例化它并使用它来存储和检索缓存中的数据。

附加技巧和窍门

以下是在 Windows 上使用 Redis 时可以使用的几个附加技巧和窍门。

管理磁盘空间

Windows 上的 Redis 会占用大量磁盘空间来持久化部分数据。尽管版本 2.8.2400 已对此进行了一些修复,但以下是如何配置 Redis 以不占用任何磁盘空间的方法

  1. 停止 Redis 服务。
  2. 删除“C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Redis”位置的所有文件,这是默认的 Redis 持久化位置。
  3. 转到 Redis 服务器配置文件。文件的默认位置是“C:\Program Files\Redis\redis.windows.conf”。
  4. 取消注释文件中的此行:save ""
  5. 注释掉这些行
    • save 900 1
    • save 300 10
    • save 60 10000
  6. 转到这一行:# persistence-available [(yes)|no]
  7. 在此下方添加此行:persistence-available [no]
  8. 保存文件并重新启动 Redis 服务。

Redis 数据库/分区

每个 Redis 实例默认包含 16 个数据库或分区。您可以在每个分区中存储相似或不同的对象。这些分区可用于分隔您的应用程序可能需要缓存的不同类型的对象。

使用 Redis 管理会话

如果您需要启动多个 Web 服务器来扩展您的 Web 应用程序,管理会话会变得有点棘手。有多种选择,例如使用粘性会话、状态服务器和 SQL 服务器。

同样,您可以使用 Redis 缓存来存储会话。有一个会话状态提供程序可以使用 Redis 缓存。以下是描述如何使用它的博客的 链接

通过命令行管理 Redis

以下是可用于通过命令行管理 Redis 的命令 术语表。位于 Redis 安装位置的 Redis-Cli.exe 可用于连接到 Redis 服务器实例。

摘要

我们已经探讨了一种在内网环境中使用的简单、直接且粗略的方法,该方法可以移植到云端并按原样使用 Azure Redis 服务。

历史

  • 初始草稿创建
© . All rights reserved.