学习Redis

学习Redis
 
我的Redis的学习参考主要集中在:
熟悉了命令之后,仔细阅读了Redis协议,总结在[Erlang 0019]Redis协议解读与实现(.Net & Erlang) ,通过协议的学习实际上有了一个心理底线:只要通过协议能够实现的功能,我们就可以在Client实现.NoSQLFan上汇集了很多优秀的Redis资料,我专门预留了一部分时间阅读上面的文章.
 
ServiceStack.Redis实践
   Redis的C#客户端我选择的是ServiceStack.Redis,相比Booksleeve redis-sharp等方案,它提供了一整套从Redis数据结构都强类型对象转换的机制;看一个例子来了解一下ServiceStack.Redis是如何组织数据的,我们使用的实体类定义如下:
复制代码
 public class User
    {
        public User()
        {
            this.BlogIds = new List<long>();
        }

        public long Id { get; set; }
        public string Name { get; set; }
        public List<long> BlogIds { get; set; }
    }
复制代码
使用下面的代码片段,我们存入两条数据到Redis:
复制代码
    using (var redisUsers = redisClient.GetTypedClient<User>())
            {
                var ayende = new User { Id = redisUsers.GetNextSequence(), Name = "Oren Eini" };
                var mythz = new User { Id = redisUsers.GetNextSequence(), Name = "Demis Bellot" };
                redisUsers.Store(ayende);
                redisUsers.Store(mythz);
              }
复制代码
我们看下Redis中的结果:
redis 127.0.0.1:6379[1]> keys *
1) "seq:User"
2) "ids:User"
3) "urn:user:1"
4) "urn:user:2"
我们逐一检查一下数据类型:
 seq:User 
string  
维护当前类型User的ID自增序列,用做对象唯一ID
 ids:User
set       
同一类型User所有对象ID的列表
 urn:user:1
string 
user对象
seq:User 维护的是类型User的ID序列 redisUsers.GetNextSequence()
复制代码
public long GetNextSequence(int incrBy)
  {
             return IncrementValueBy(SequenceKey, incrBy);
  }
 public long IncrementValue(string key)
    {
              return client.Incr(key);
     }
复制代码
这里的SequenceKey就是 "seq:User",然后我们通过存一个对象到Redis看另外两个key是什么作用:
复制代码
 public T Store(T entity)
        {
            var urnKey = entity.CreateUrn();
            this.SetEntry(urnKey, entity);

            return entity;
        }
        //entity.CreateUrn();的结果是"urn:user:1"
        public void SetEntry(string key, T value)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            client.Set(key, SerializeValue(value));
            client.RegisterTypeId(value);
        }

        internal void RegisterTypeId<T>(T value)
        {
            var typeIdsSetKey = GetTypeIdsSetKey<T>();
            var id = value.GetId().ToString();

            if (this.Pipeline != null)
            {
                var registeredTypeIdsWithinPipeline = GetRegisteredTypeIdsWithinPipeline(typeIdsSetKey);
                registeredTypeIdsWithinPipeline.Add(id);
            }
            else
            {
                this.AddItemToSet(typeIdsSetKey, id);
            }
        }
复制代码
这里的typedIdsSetKey 就是"ids:User
 
ids:User相当于一个索引,包含了所有同为类型User的ID;由于维护了这样一个分组信息,所以很容易实现GetAll<User>()这样的功能;
 
在redis-cli中查询一下 get urn:user:1 返回值是 JSON格式:
"{\"Id\":1,\"Name\":\"Oren Eini\",\"BlogIds\":[1]}"
 
ServiceStack.Redis 自己实现了一套序列化功能, Fastest JSON Serializer for .NET released  支持 POCO(Plain Old CLR Object)序列化.
 
   实际应用中,由于我们使用的数据是来自关系型数据库,本身包含关联关系,所以并不需要这样的对象组织方式;我们只需要把关系型数据中一对多的关系在Redis中表达出来即可;这里我扩展修改了RedisClient的实现,由于RedisClient本身已经通过 partial方式 分割成若干个文件,所以很容易把变动的代码集中在同一个代码文件中.具体业务对象存储,主帖和回帖会有字段级修改,所以设计成为Hash结构,其它几个子对象读写都是以对象为单位,设计成为POCO方式持久化;

使用管道Pipeline遇到的问题
 
  使用管道可以将客户端到Redis的往返次数减少,不过在使用ServiceStack.Redis的时候,遇到这样一个问题,比如要把一个List<log>全部存储,代码不可以写成下面这样:
复制代码
%%第一种写法 
           logs.ForEach(n =>
                {
                    pipeline.QueueCommand(r =>
                    {
                        ((RedisClient)r).Store<OpLog>(n, n.GetObjectID(), n.GetUrnKey());
                        ((RedisClient)r).Expire(n.GetUrnKey(), dataLifeTime);
                    });
                });
复制代码
而是要写成这样:
复制代码
%%第二种写法
 logs.ForEach(n =>
                {
  
                    pipeline.QueueCommand(r => ((RedisClient)r).Store<Log>(n, n.ID, n.GetUrnKey()));
                    pipeline.QueueCommand(r => ((RedisClient)r).Expire(n.GetUrnKey(), dataLifeTime));

                });
复制代码
什么原因呢?RedisQueueCompletableOperation的AddCurrentQueuedOperation方法会在 执行CurrentQueuedOperation = null;如果按照第一种写法会丢失回调函数,这就造成有返回值在没有及时提取,后续的操作获取返回值时首先取到的是积压的结果信息,就出现了异常,而第二种写法就避免了这个问题.
  protected virtual void AddCurrentQueuedOperation()
        {
            this.QueuedCommands.Add(CurrentQueuedOperation);
            CurrentQueuedOperation = null;
        }
Redis工具篇
  Redis的客户端redis-cli不是太好用,退格键和箭头都不能正常使用,这个的确影响效率,还是需要找一个合适的工具,我比较喜欢这个: RedisConsole
 这个工具用来学习是很好用的,但是数据量一旦增大,左侧列表就混乱了,而且一点击就假死;所以建议只在学习阶段使用;

在没有window的环境,启动一个Erlang的客户端也是一个不错的选择.
 
Web端的管理工具我选用的是 Redis Admin UI
这个ServiceStack.Redis的配套项目,修改一下web.config就能用,地址在此: http://www.servicestack.net/mythz_blog/?p=381



 
刚刚在NOSQLFan上看到一篇<Memcached真的过时了吗?>一定要转过来:

这两年Redis火得可以,Redis也常常被当作Memcached的挑战者被提到桌面上来。关于Redis与Memcached的比较更是比比皆是。然而,Redis真的在功能、性能以及内存使用效率上都超越了Memcached吗?

下面内容来自Redis作者在stackoverflow上的一个回答,对应的问题是《Is memcached a dinosaur in comparison to Redis?》(相比Redis,Memcached真的过时了吗?)

  • You should not care too much about performances. Redis is faster per core with small values, but memcached is able to use multiple cores with a single executable and TCP port without help from the client. Also memcached is faster with big values in the order of 100k. Redis recently improved a lot about big values (unstable branch) but still memcached is faster in this use case. The point here is: nor one or the other will likely going to be your bottleneck for the query-per-second they can deliver.
  • 没有必要过多的关心性能,因为二者的性能都已经足够高了。由于Redis只使用单核,而Memcached可以使用多核,所以在比较上,平均每一个核上Redis在存储小数据时比Memcached性能更高。而在100k以上的数据中,Memcached性能要高于Redis,虽然Redis最近也在存储大数据的性能上进行优化,但是比起Memcached,还是稍有逊色。说了这么多,结论是,无论你使用哪一个,每秒处理请求的次数都不会成为瓶颈。(比如瓶颈可能会在网卡)
  • You should care about memory usage. For simple key-value pairs memcached is more memory efficient. If you use Redis hashes, Redis is more memory efficient. Depends on the use case.
  • 如果要说内存使用效率,使用简单的key-value存储的话,Memcached的内存利用率更高,而如果Redis采用hash结构来做key-value存储,由于其组合式的压缩,其内存利用率会高于Memcached。当然,这和你的应用场景和数据特性有关。
  • You should care about persistence and replication, two features only available in Redis. Even if your goal is to build a cache it helps that after an upgrade or a reboot your data are still there.
  • 如果你对数据持久化和数据同步有所要求,那么推荐你选择Redis,因为这两个特性Memcached都不具备。即使你只是希望在升级或者重启系统后缓存数据不会丢失,选择Redis也是明智的。
  • You should care about the kind of operations you need. In Redis there are a lot of complex operations, even just considering the caching use case, you often can do a lot more in a single operation, without requiring data to be processed client side (a lot of I/O is sometimes needed). This operations are often as fast as plain GET and SET. So if you don’t need just GEt/SET but more complex things Redis can help a lot (think at timeline caching).
  • 当然,最后还得说到你的具体应用需求。Redis相比Memcached来说,拥有更多的数据结构和并支持更丰富的数据操作,通常在Memcached里,你需要将数据拿到客户端来进行类似的修改再set回去。这大大增加了网络IO的次数和数据体积。在Redis中,这些复杂的操作通常和一般的GET/SET一样高效。所以,如果你需要缓存能够支持更复杂的结构和操作,那么Redis会是不错的选择。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值