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( ...
随机推荐
- 电子科大POJ "3*3矩阵的乘法"
3阶矩阵的乘法 Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others) c-source ...
- POJ1679(次小生成树)
The Unique MST Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 24201 Accepted: 8596 D ...
- Pros and Cons of T4 in Visual Studio 2008
Oleg Sych - » Pros and Cons of T4 in Visual Studio 2008 Pros and Cons of T4 in Visual Studio 2008 Po ...
- javax.mail用smtp服务器发送带附件的邮件
jar包: javax.mail-1.5.5.jar maven配置: <dependency> <groupId>com.sun.mail</groupId> & ...
- centos网速特别慢的最佳解决的方法 - 关闭ipv6
我使用了centOS,可是发现网速实在是卡得差点儿不能上网,连百度都打不开,可是win却飞快. 后来想到偶然记得有一次看过一段话,说到关闭ipv6,測试来一下,果然有效,关闭来ipv6打开网速飞快. ...
- 命令行分析java线程CPU占用
1.使用top命令找出占用cpu最高的JAVA进程pid号 2. 找出占用cpu最高的线程: top -Hp -n 1 3. 打印占CPU最高JAVA进程pid的堆栈信息 jstack pid &g ...
- 事关Animation Tree的工作随笔(一)
最近的业务上,又回到Animation Tree这块了. 众所周知的是Animation Tree这些概念已经提出很久了,但是使用有着AT支持的CE引擎的项目,却依然义无反顾地没有使用AT,而且,连某 ...
- .Net类型与JSON的映射关系
首先谢谢大家的支持和关注.本章主要介绍.Net类型与JSON是如何映射的.我们知道JSON中类型基本上有三种:值类型,数组和对象.而.Net中的类型比较多.到底它们是如何映射的呢? 总体来讲,Json ...
- react tab选项卡切换
Tab选项卡切换是个很常见也很简单的小功能,用原生js和jq去写的话可能不到20行代码就搞定so easy.但是用react去实现就没那么容易了(是自己react比较菜).由于最近在重新学习react ...
- C++程序设计实践指导1.6分数运算改写要求实现
改写要求:重载>>和<<实现分数类对象的直接输入输出,重载+完成多个分数对象加法 #include <cstdlib> #include <iostream& ...