注:关于如何在windows,linux下配置redis,详见这篇文章:)

目前网上有一些链接Redis的C#客户端工具,这里介绍其中也是目前我们企业版产品中所使用的ServiceStackRedis, 链接地址:

https://github.com/mythz/ServiceStack.Redis

下面该链接中的源码包或dll文件,引入到项目中,并添加如下名空间引用(仅限本文):

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

注:ServiceStackRedis封装了大量方法和对象,这里只摘有代表性的内容介绍,更多内容参见其官方文档。
 
    声明一个客户端对象:
    protected RedisClient Redis = new RedisClient("10.0.4.227", 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);//移除指定索引位置数据

二.存储对象:

    public class UserInfo
    {
        public long Id { set; get; }
        public string UserName { get; set; }
        public int 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));
  }

四.使用客户端链接池模式提升链接速度:


  public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
  {
       //支持读写分离,均衡负载
       return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
       {
           MaxWritePoolSize = 5,//“写”链接池链接数
           MaxReadPoolSize = 5,//“写”链接池链接数
           AutoStart = true,
       });          
  }

声明链接池对象(这里只使用一个redis服务端):


  PooledRedisClientManager prcm = CreateManager(new string[] { "10.0.4.210:6379" }, new string[] { "10.0.4.210: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("10.0.4.227", 6379);

这样在redis服务端显示只有一个客户链接

3.与memcached测试过程中发现,在存储时两者效率接近(使用本文第一种方式),在取数据时memcached速度比redis要快一些(毫秒级差异),这一点并不像网上一些文章所说的那样,看来在实际开发和生产环境下还要以使用背景及结果为准。

测试代码下载链接:

/Files/daizhj/Redis.Sample.rar

使用ServiceStackRedis链接Redis简介的更多相关文章

  1. 使用ServiceStackRedis链接Redis简介 [转]

      注:关于如何在windows,linux下配置redis,详见这篇文章:)          Discuz!NT中的Redis架构设计 目前网上有一些链接Redis的C#客户端工具,这里介绍其中也 ...

  2. 分布式缓存技术redis学习系列(一)——redis简介以及linux上的安装

    redis简介 redis是NoSQL(No Only SQL,非关系型数据库)的一种,NoSQL是以Key-Value的形式存储数据.当前主流的分布式缓存技术有redis,memcached,ssd ...

  3. 分布式缓存技术redis学习(一)——redis简介以及linux上的安装

    redis简介 redis是NoSQL(No Only SQL,非关系型数据库)的一种,NoSQL是以Key-Value的形式存储数据.当前主流的分布式缓存技术有redis,memcached,ssd ...

  4. 分布式缓存技术redis系列(一)——redis简介以及linux上的安装

    redis简介 redis是NoSQL(No Only SQL,非关系型数据库)的一种,NoSQL是以Key-Value的形式存储数据.当前主流的分布式缓存技术有redis,memcached,ssd ...

  5. 1.Redis简介/配置文件

    redis简介 redis使用入门 redis安装 http://www.runoob.com/redis/redis-install.html [root@yz---- bin]# ll total ...

  6. 01 . Redis简介及部署主从复制

    简介 Remote Dictionary Server, 翻译为远程字典服务, Redis是一个完全开源的基于Key-Value的NoSQL存储系统,他是一个使用ANSIC语言编写的,遵守BSD协议, ...

  7. NoSQL和Redis简介及Redis在Windows下的安装和使用教程

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/103.html?1455869099 NoSQL简介 介绍redis前,我 ...

  8. Redis简介、与memcached比较、存储方式、应用场景、生产经验教训、安全设置、key的建议、安装和常用数据类型介绍、ServiceStack.Redis使用(1)

    1.NOSQL简介 nosql的产生并不是要彻底的代替关系型数据库,而是作为传统关系型数据库的一个补充. Facebook和360使用Cassandra来存储海量社交数据 Twitter在其url抓取 ...

  9. redis的单实例配置+web链接redis

    [root@cache01 src]# wget http://download.redis.io/redis-stable.tar.gz [root@cache01 src]# tar -xzvf ...

随机推荐

  1. SQL重复记录查询(转载)

     1.查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断 select * from people )  例二:  select * from testtable  where ...

  2. Linux内核树的建立-基于ubuntu系统

    刚看 O'REILLY 写的<LINUX 设备驱动程序>时.作者一再强调在编写驱动程序时必须 建立内核树.先前的内核只需要有一套内核头文件就够了,但因为2.6的内核模块吆喝内核源码树中的目 ...

  3. MVC-HtmlHelper扩展

    1.添加对System.Web.Mvc的引用 2.添加一个静态类,里面的扩展方法也必须是静态的 //HtmlHelper扩展类 //添加对System.Web.Mvc的引用 //命名空间:System ...

  4. approval workflow in sharepoint designer

    http://office.microsoft.com/en-us/sharepoint-designer-help/video-create-an-approval-workflow-in-shar ...

  5. mybatis generator自动生成 实体类, sqlmap配置文件 详细介绍

    我使用的是Eclipse Luna 装了自己常用的插件, generator也是其中一个推荐下载 MyBatis_Generator_1.3.1.zip离线安装包 <?xml version=& ...

  6. EF4.1之复杂类型

    首先我们生成两张对应表: public class Client { public int ClientID { set; get; } public string ClientName { set; ...

  7. linux tail

    tail 命令从指定点开始将文件写到标准输出,使用tail命令的-f选项可以方便的查阅正在改变的日志文件,tail -f filename会把filename里最尾部的内容显示在屏幕上,并且不但刷新, ...

  8. ios设备 分辨率(转)

    1 iOS设备的分辨率 iOS设备,目前最主要的有3种(Apple TV等不在此讨论),按分辨率分为两类 iPhone/iPod Touch 普屏分辨率    320像素 x 480像素 Retina ...

  9. hdu 3714 Error Curves(三分)

    http://acm.hdu.edu.cn/showproblem.php?pid=3714 [题意]: 题目意思看了很久很久,简单地说就是给你n个二次函数,定义域为[0,1000], 求x在定义域中 ...

  10. POJ - 1741 Tree

    DescriptionGive a tree with n vertices,each edge has a length(positive integer less than 1001).Defin ...