標籤:soft int type write rem 選擇 cli hang main
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.Get<int>("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必須是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