C#客户端Redis服务器的分布式缓存

2019-12-30 11:51:33于丽

请确保有足够的权限启动该服务。安装完毕后,请检查该服务是否创建成功,当前是否正在运行:

C#,Redis,分布式缓存

或者,你可以使用安装程序(我没试过):https://www.easck.com/p>

首先,找到这行:

# requirepass foobared

删除开头的#符号,用新密码替换foobared:

requirepass foobared

然后,重新启动Redis Windows服务!

当具体使用客户端的时候,使用带密码的构造函数:

RedisClient client = new RedisClient(serverHost, port, redisPassword);

Redis服务器复制(主—从配置)

Redis支持主从同步,即,每次主服务器修改,从服务器得到通知,并自动同步。大多复制用于读取(但不能写)扩展和数据冗余和服务器故障转移。设 置两个Redis实例(在相同或不同服务器上的两个服务),然后配置其中之一作为从站。为了让Redis服务器实例是另一台服务器的从属,可以这样更改配 置文件:

找到以下代码:

# slaveof <masterip> <masterport>

替换为:

slaveof 192.168.1.1 6379

(可以自定义指定主服务器的真实IP和端口)。如果主服务器配置为需要密码(验证),可以如下所示改变redis.conf,找到这一行代码:

# masterauth <master-password>

删除开头的#符号,用主服务器的密码替换<master-password>,即:

masterauth mastpassword

现在这个Redis实例可以被用来作为主服务器的只读同步副本。

用C#代码使用Redis缓存

用C#代码使用Redis运行Manage NuGet包插件,找到ServiceStack.Redis包,并进行安装。

C#,Redis,分布式缓存

直接从实例化客户端使用Set/Get方法示例:

 



    string host = "localhost";  string elementKey = "testKeyRedis";    using (RedisClient redisClient = new RedisClient(host))  {        if (redisClient.Get<string>(elementKey) == null)        {             // adding delay to see the difference             Thread.Sleep(5000);             // save value in cache             redisClient.Set(elementKey, "some cached value");        }        // get value from the cache by key        message = "Item value is: " + redisClient.Get<string>("some cached value");  }