Redis 实践笔记
本文来自:http://www.cnblogs.com/me-sa/archive/2012/03/13/redis-in-action.html
最近在项目中实践了一下Redis,过程中遇到并解决了若干问题,记录之.

我们这个项目是对原有缓存系统的改进,应用场景是论坛发帖,回帖,置顶,以及操作日志等等;原有系统会有替换算法把内存缓存一部分冷数据逐渐从内存中换出,内存对象序列化为XML文件持久化到磁盘;内存缓存一方面是为了访问速度,一方面是为后端的DB分担访问压力;而XML文件缓存则是为了避免雪崩,即当系统重启的时候由于缓存没有填充完毕,大量相同的请求会冲击到后端的DB;最初接手项目的时候,被告知公司老大要求xml 文件缓存必须保留,呵呵,通过和老大沟通其实保留文件缓存就是为了解决雪崩.
了解原有系统的瓶颈是第一步,原有系统主要问题是:
- 官方网站 http://redis.io/
- Redis命令 http://redis.io/commands
- Redis协议 http://redis.io/topics/protocol
- NoSQLFan Redis资料汇总专题 http://blog.nosqlfan.com/html/3537.html

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; }
}


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 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对象
|

public long GetNextSequence(int incrBy)
{
return IncrementValueBy(SequenceKey, incrBy);
}
public long IncrementValue(string key)
{
return client.Incr(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);
}
}


%%第一种写法
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)); });

protected virtual void AddCurrentQueuedOperation()
{
this.QueuedCommands.Add(CurrentQueuedOperation);
CurrentQueuedOperation = null;
}

这两年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会是不错的选择。
注意:实践版本 Redis 2.4.9
Rdbtools is a parser for Redis' dump.rdb files. The parser generates events similar to an xml sax parser, and is very efficient memory wise.
In addition, rdbtools provides utilities to :
- Generate a Memory Report of your data across all databases and keys
- Convert dump files to JSON
- Compare two dump files using standard diff tools
Redis 实践笔记的更多相关文章
- Celery配置实践笔记
说点什么: 整理下工作中配置celery的一些实践,写在这里,一方面是备忘,另外一方面是整理成文档给其他同事使用. 演示用的项目,同时也发布在Github上: https://github.com/b ...
- redis 学习笔记(6)-cluster集群搭建
上次写redis的学习笔记还是2014年,一转眼已经快2年过去了,在段时间里,redis最大的变化之一就是cluster功能的正式发布,以前要搞redis集群,得借助一致性hash来自己搞shardi ...
- Redis学习笔记~目录
回到占占推荐博客索引 百度百科 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合). ...
- Redis学习笔记4-Redis配置详解
在Redis中直接启动redis-server服务时, 采用的是默认的配置文件.采用redis-server xxx.conf 这样的方式可以按照指定的配置文件来运行Redis服务.按照本Redi ...
- Redis学习笔记7--Redis管道(pipeline)
redis是一个cs模式的tcp server,使用和http类似的请求响应协议.一个client可以通过一个socket连接发起多个请求命令.每个请求命令发出后client通常会阻塞并等待redis ...
- 节约内存:Instagram的Redis实践(转)
一.问题: 数据库表数据量极大(千万条),要求让服务器更加快速地响应用户的需求. 二.解决方案: 1.通过高速服务器Cache缓存数据库数据 2.内存数据库 三.主流解Ca ...
- redis入门笔记(2)
redis入门笔记(2) 上篇文章介绍了redis的基本情况和支持的数据类型,本篇文章将介绍redis持久化.主从复制.简单的事务支持及发布订阅功能. 持久化 •redis是一个支持持久化的内存数据库 ...
- redis入门笔记(1)
redis入门笔记(1) 1. Redis 简介 •Redis是一款开源的.高性能的键-值存储(key-value store).它常被称作是一款数据结构服务器(data structure serv ...
- Redis学习笔记一:数据结构与对象
1. String(SDS) Redis使用自定义的一种字符串结构SDS来作为字符串的表示. 127.0.0.1:6379> set name liushijie OK 在如上操作中,name( ...
随机推荐
- Repeated DNA Sequences 解答
Question All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: ...
- UVA 11111-Generalized Matrioshkas(栈)
题意:有很多层盒子,盒子里面再套盒子,一个盒子可能套多个独立的子盒子,但子盒子的总体积必须小于该盒子,否则不合法,输入给一行数,负数代表左边,正数代表右边,大小表示其体积,如-2,-1,1,2则表示体 ...
- 【转】android电池(五):电池 充电IC(PM2301)驱动分析篇
关键词:android 电池 电量计 PL2301任务初始化宏 power_supply 中断线程化 平台信息:内核:linux2.6/linux3.0系统:android/android4.0 ...
- php使用PDO方法详解
PDO::exec:返回的是int类型,表示影响结果的条数. 复制代码 代码如下: PDOStatement::execute 返回的是boolean型,true表示执行成功,false表示执行失败, ...
- 格而知之5:我所理解的Run Loop
1.什么是Run Loop? (1).Run Loop是线程的一项基础配备,它的主要作用是来让某一条线程在有任务的时候工作.没有任务的时候休眠. (2).线程和 Run Loop 之间的关系是一一对应 ...
- linux 在批处理中,完整路径有空格的处理方式(加引號)
cp -f E:/XML_EDITOR/xmleditor25/xmleditor/Editor_UIOuterCtrl/TraceViewDlg.cpp E:/XML_EDITOR/'XMLEdit ...
- HDU 4333 Revolving Digits 扩展KMP
链接:http://acm.hdu.edu.cn/showproblem.php?pid=4333 题意:给以数字字符串,移动最后若干位到最前边,统计得到的数字有多少比原来大,有多少和原来同样,有多少 ...
- linux下挂载iso镜像文件(转)
挂接命令(mount) 首先,介绍一下挂接(mount)命令的使用方法,mount命令参数非常多,这里主要讲一下今天我们要用到的. 命令格式: mount [-t vfstype] [-o optio ...
- 【计算几何初步-凸包-Jarvis步进法。】【HDU1392】Surround the Trees
[科普]什么是BestCoder?如何参加? Surround the Trees Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65 ...
- 什么时候会刷新备库控制文件refresh the standby database control file?
通过合理的设置,对于Primary的绝大数操作,都是可以传递到Physical Standby,datafile的操作是通过STANDBY_FILE_MANAGEMENT参数来控制的,但是即使STAN ...