C#使用Redis集群作为缓存服务器

简介

基于 abp.net 框架的缓存模块,如何使用 Redis 集群来实现案例呢?


项目结构

类型:Console
依赖类库:Abp.RedisCache、Abp


主要代码

1.程序模块

根据 abp 编码规则,定义 console 的模块


    /// <summary>
    /// reids 集群测试 module
    /// </summary>
    [DependsOn(typeof(AbpRedisCacheModule))]
    public class ReidsSentinelCacheModule : AbpModule
    {
        public override void PreInitialize()
        {
            this.Configuration.Caching.ConfigureAll(cache =>
                {
                    //cache.DefaultSlidingExpireTime = TimeSpan.FromMinutes(1);// 多久未访问
                    // 设置 1min 缓存失效
                    cache.DefaultAbsoluteExpireTime = TimeSpan.FromMinutes(1);// 定时销毁
                });
            this.Configuration.Caching.UseRedis();

        }
    }
2.初始化 ABP

        /// <summary>
        ///     初始化 abp
        /// </summary>
        private static void InitAbp()
        {
            var bootstrapper = AbpBootstrapper.Create<ReidsSentinelCacheModule>();
            bootstrapper.Initialize();
            _cacheManager = IocManager.Instance.Resolve<ICacheManager>();
        }
3.可配置 console 标题

        private static void InitConsole()
        {
            var title= ConfigurationManager.AppSettings["title"];
            Console.Title = title.IsNullOrEmpty() ? "master" : title;
        }
4.取值

        /// <summary>
        ///     获取缓存值
        /// </summary>
        /// <returns>随机值</returns>
        public static int GetCacheItem()
        {
            var cache = _cacheManager.GetCache("RANDOMCACHE");
            
            return int.Parse((cache.Get(
                "RandomValue",
                () =>
                {
                    Console.WriteLine("非缓存数据");
                    Random rd = new Random();
                    return rd.Next(1, 100000);
                })).ToString());
        }
5.main 方法

        static void Main(string[] args)
        {
            InitConsole();
            InitAbp();
            
            var randomValue = GetCacheItem();
            Console.WriteLine("第一次取值:{0}",randomValue);
            
            Stopwatch watch = new Stopwatch();
            watch.Start();
            while (true)
            {
                Thread.Sleep(5000); // 等待 500ms
                // 每 500 ms 取一次
                randomValue = GetCacheItem();
                Console.WriteLine("{1}取值:{0}", randomValue, DateTime.Now.ToString("HH:mm:ss.fff"));

                if (watch.ElapsedMilliseconds > 10*60 * 1000)
                {
                    // 运行 1min
                    break;
                }
            }

            watch.Stop();

            Console.ReadKey(true);
        }

程序运行 10min,每 5s 取一次数据,缓存设定定时 1min 失效!

6.配置文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    
  </configSections>
  <appSettings>
    <!--区分程序-->
    <add key="title" value="" />
    <!--指定 redis 数据库-->
    <add key="Abp.Redis.Cache.DatabaseId" value="-1" />
    
  </appSettings>
  <connectionStrings>
    <!--设置 redis 数据库连接-->
    <add name="Abp.Redis.Cache" connectionString="localhost:6379,localhost:6380,localhost:6381"/>
  </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

运行结果

现在我们运行三个程序,标题分别为 master、slavo1、slavo2,将生产的 debug 文件夹复制三个,分别重命名

C#使用 Redis 集群作为缓存服务器
图片.png

修改三个文件夹配置文件: <add key="title" value="" />来指定 console 显示的标题。

期望结果

分别运行 三个程序,期望得到的结果是:master、s1、s2 获取到的缓存数据都是一样的,并且如果 三个程序,有一个改变了缓存,其他程序也能正确获取到缓存值,运行结果如下:

C#使用 Redis 集群作为缓存服务器
图片.png

 

我们发现 master 第一次产生的数据:76347,而其他程序启动之后,没有显示非缓存数据,而是直接取缓存数据 76347,得到预期运行结果。

master 关闭,

接下来,我们 stop master

C#使用 Redis 集群作为缓存服务器
图片.png

 

在来看程序运行结果

C#使用 Redis 集群作为缓存服务器
图片.png

 

程序正常运行


总结

通过该实例,我们发现,可以正常使用 redis 集群缓存,并且学习了 abp 的基本用法和 abp.rediscache 的用法。
为什么要用三个同样的程序跑呢?为了以后 web 做负载均衡的时候,能够确保每个程序都会正确的读取到缓存数据,经过实验证明,方案是可行的。


来源:https://www.jianshu.com/p/20d9dfc01747

示例源代码:https://git.oschina.net/zhaord/redis_sentinel_demo.git

© 版权声明

☆ END ☆
喜欢就点个赞吧
点赞0 分享
图片正在生成中,请稍后...