.NET 用戶端串連Redis 介紹

來源:互聯網
上載者:User

C#寫的用戶端類型主要有:

ServiceStack.Redis ★  https://github.com/ServiceStack/ServiceStack.Redis  
Booksleeve ★   http://code.google.com/p/booksleeve/  
Sider  http://nuget.org/List/Packages/Sider  
TeamDev Redis Client  http://redis.codeplex.com/  
redis-sharp   https://github.com/migueldeicaza/redis-sharp

加星號的是使用率高的項目。參考:http://redis.io/clients

以ServiceStack.Redis為例

引入到項目中,並添加如下名空間引用(僅限本文):

using ServiceStack.Common.Extensions;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
using ServiceStack.Text;
using ServiceStack.Redis.Support;

註:ServiceStackRedis封裝了大量方法和對象,這裡只摘有代表性的內容介紹,更多內容參見其官方文檔。

聲明一個用戶端對象:
protected RedisClient Redis = new RedisClient("127.0.0.1", 6379);//redis服務IP和連接埠


一 .基本KEY/VALUE索引值對操作:
1. 添加/擷取:

List<string> storeMembers =new List<string>();
storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x));
註:也可直接使用AddRangeToList方法將一組資料裝入如:

Redis.AddRangeToList("addarrangetolist", storeMembers);

2. 擷取資料

var members = Redis.GetAllItemsFromList("additemtolist");
members.ForEach(s => Response.Write("<br/>additemtolist :"+ s));

3. 擷取指定索引位置資料

var item = Redis.GetItemFromList("addarrangetolist", 2);

4. 移除:

var list = Redis.Lists["addarrangetolist"];
list.Clear();//清空
list.Remove("two");//移除指定索引值
list.RemoveAt(2);//移除指定索引位置資料


二.儲存物件:

publicclass UserInfo
{
publiclong Id { set; get; }
publicstring UserName { get; set; }
publicint Age { get; set; }
}

1.通常方式(底層使用json序列化):

Redis.Set<UserInfo>("userinfo", new UserInfo() { UserName ="李四", Age =45 });
UserInfo userinfo = Redis.Get<UserInfo>("userinfo");

註:當然上面方式也適合於基本類型,如:

Redis.Set<int>("my_age", 12);//或Redis.Set("my_age", 12);
int age = Redis.Get<int>("my_age");


2.object序列化方式儲存:


var ser =new ObjectSerializer(); //位於namespace ServiceStack.Redis.Support;
bool result = Redis.Set<byte[]>("userinfo", ser.Serialize(new UserInfo() { UserName ="張三", Age =12 }));
UserInfo userinfo = ser.Deserialize(Redis.Get<byte[]>("userinfo")) as UserInfo;
//也支援列表
Redis.Set<byte[]>("userinfolist_serialize", ser.Serialize(userinfoList));
List<UserInfo> userList = ser.Deserialize(Redis.Get<byte[]>("userinfolist_serialize")) as List<UserInfo>;

需要說明的是在測試過程中發現JSON序列化的效率要比object序列化高一些。

三.儲存表格對象,比如:

 

using (var redisUsers = Redis.GetTypedClient<UserInfo>())
{
redisUsers.Store(new UserInfo { Id = redisUsers.GetNextSequence(), UserName ="daizhj", Age =12 });
redisUsers.Store(new UserInfo { Id = redisUsers.GetNextSequence(), UserName ="daizhenjun", Age =13 });

var allUsers = redisUsers.GetAll();//就像操作ado對象一樣,可以進行CRUD等操作
allUsers.ForEach(s => Response.Write("<br/>user :"+ s.UserName +" age:"+ s.Age));
}


四.使用用戶端連結池模式提升連結速度:

 

publicstatic PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
{
//支援讀寫分離,均衡負載
returnnew PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
{
MaxWritePoolSize =5,//“寫”連結池連結數
MaxReadPoolSize =5,//“寫”連結池連結數
AutoStart =true,
}); 
}

聲明連結池對象(這裡只使用一個redis服務端):


PooledRedisClientManager prcm = CreateManager(newstring[] { "127.0.0.1:6379" }, newstring[] { "127.0.0.1:6379" });

List<UserInfo> userinfoList =new List<UserInfo>();
userinfoList.Add(new UserInfo() { UserName ="pool_daizhj", Age =1 });
userinfoList.Add(new UserInfo() { UserName ="pool_daizhj1", Age =2 });

從池中擷取一個連結:

using (IRedisClient Redis = prcm.GetClient())

Redis.Set("userinfolist", userinfoList);
List<UserInfo> userList = Redis.Get<List<UserInfo>>("userinfolist");
}


註:
1.前三種方式我在本地測試發現存取效率從高到底,具體原因還待分析。

2.如只想使用長連結而不是連結池的話,可以直接將下面對象用static方式聲明即可: 
protected static RedisClient Redis = new RedisClient("127.0.0.1", 6379);

這樣在redis服務端顯示只有一個客戶連結

3.與memcached測試過程中發現,在儲存時兩者效率接近(使用本文第一種方式),在取資料時memcached速度比redis要快一些(毫秒級差異),這一點並不像網上一些文章所說的那樣,看來在實際開發和生產環境下還要以使用背景及結果為準。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.