c# redis 操作类库推荐:StackExchange.Redis.Extensions
2021-02-13 14:17
StackExchange是一个优秀的c# redis客户端,但是存在操作略为繁琐的弊端,为了简化操作,使用 StackExchange.Redis.Extensions成为了一个非常值得推荐的选择。它能让使用StackExchange变得相当简单。
StackExchange.Redis.Extensions github地址:https://github.com/imperugo/StackExchange.Redis.Extensions
第一步用nuget安装相关包:
PM> Install-Package StackExchange.Redis.Extensions.Newtonsoft
完成后即可使用。
以下将用一个多线程修改某一个值的控制台案例来作为演示。
using System; using System.Threading; using StackExchange.Redis.Extensions.Core; using StackExchange.Redis.Extensions.Core.Configuration; using StackExchange.Redis.Extensions.Newtonsoft; namespace Redis { class Program { public static void Ins() { Thread thread = new Thread(() => { for (int i = 0; i 1000; i++) { client.Database.StringIncrement("key"); } }); thread.Start(); } private static StackExchangeRedisCacheClient client; static void Main(string[] args) { var redisConfiguration = new RedisConfiguration() //配置 { Hosts = new RedisHost[] { new RedisHost(){Host = "127.0.0.1",Port = 6379} } }; client = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(),redisConfiguration ); client.Add("key", 0); for (int j = 0; j 10; j++) { Ins(); } Thread.Sleep(2000); int i = client.Getint>("key"); Console.WriteLine(i); Console.ReadKey(); } } }
值得注意的是,如果要把相关配置写进app.config或者web.config,需要另外再安装一个包:StackExchange.Redis.Extensions.LegacyConfiguration
Install-Package StackExchange.Redis.Extensions.LegacyConfiguration
然后配置文件就可以写相关配置了:
xml version="1.0" encoding="utf-8"?> configuration> configSections> section name="redisCacheClient" type="StackExchange.Redis.Extensions.LegacyConfiguration.RedisCachingSectionHandler, StackExchange.Redis.Extensions.LegacyConfiguration" /> configSections> redisCacheClient allowAdmin="true" ssl="false" connectTimeout="3000" database="24"> serverEnumerationStrategy mode="Single" targetRole="PreferSlave" unreachableServerAction="IgnoreIfOtherAvailable" /> hosts> add host="127.0.0.1" cachePort="6379" /> hosts> redisCacheClient> configuration>
然后在代码里用RedisCachingSectionHandler.GetConfig()获得配置:
var config = RedisCachingSectionHandler.GetConfig(); client = new StackExchangeRedisCacheClient(new NewtonsoftSerializer(),config );
文章标题:c# redis 操作类库推荐:StackExchange.Redis.Extensions
文章链接:http://soscw.com/index.php/essay/54867.html