{人面不知何去处 桃花依旧笑春风}

redis的几个问题

Posted in Uncategorized by interma on 2013/03/13

没事读了一下hunangz的《redis设计与实现》
http://www.redisbook.com/en/latest/

写的很好,文档格式还特别好看,列几个有意思的点。

1,sds,Simple Dynamic String,要解决什么问题?
http://www.redisbook.com/en/latest/internal-datastruct/sds.html#redis

2,dictht/哈希表的结构
http://www.redisbook.com/en/latest/internal-datastruct/dict.html#id5
有个图,一看就懂~

3,rehash为什么要渐进进行?它的实现过程。
http://www.redisbook.com/en/latest/internal-datastruct/dict.html#id18
补充说明一下,python中的dict resize时就不是渐进的,set/insert item时有可能要调整。

4,rehash时的多线程竞争?
redis单线程。。。

5,温习skiplist
http://www.redisbook.com/en/latest/internal-datastruct/skiplist.html

6,ziplist的目的?以及实现
http://www.redisbook.com/en/latest/compress-datastruct/ziplist.html

7,redis的key为什么要加上类型?
http://www.redisbook.com/en/latest/datatype/object.html

8,亲切的小整数池
http://www.redisbook.com/en/latest/datatype/object.html#id3

9,redis的事务保证ACID了吗?
http://www.redisbook.com/en/latest/feature/transaction.html#acid
其中的I有可能影响并发能力。
温习一下ACID:
from http://en.wikipedia.org/wiki/ACID#Atomicity
-Atomicity requires that each transaction is “all or nothing”: if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged.
原子性:全做/全不做
-The consistency property ensures that any transaction will bring the database from one valid state to another.
一致性:有效状态间迁移,不会跳到无效态(很久之前的有效态也算数)
-The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially, i.e. one after the other.
隔离性:等效于某种顺序执行
-Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors.
持久性:一旦提交,全力保障永久有效。

10,lua脚本的安全性考虑
http://www.redisbook.com/en/latest/feature/scripting.html#id2

Tagged with: ,

后端服务程序优化

Posted in Uncategorized by interma on 2013/03/08

参考xiaowei PPT整理。

one rule:没有前提假设,就没有优化方案。

一,内存分配+多线程算法
问题,@glibc
1,多线程分配慢:为了线程安全,加lock;线程级缓存内存,tcmalloc
2,碎片化:直接划出一块慢慢切分。

解决方法
3,短生命周期Vs长生命周期:如php,不需要太精巧的分配手段。
4,定长分配:freelist。
5,变长分配:多级定长池,巨大内存直接malloc。
6,常用数据结构优化:
a,hash:节点空间连续化(写不友好)
b,链表:类似hash,连续化,少用next指针。
c,动态数组:1维转2维,随用新增。
7,内存回收:
延时释放,依赖工程经验。
小tip:48bit指针,16bit引用计数,配合内存池。
8,实例:
一写多读线程安全链表:依赖next指针的调整顺序,lock-free,CAS。
多写多读hash表:由如上链表组成,针对每个slot设置锁,写冲突概率低。但是锁内存开销大,可以多个slot映射到一个锁来节省空间。多线程下性能佳。

二,磁盘io
传统硬盘原理:seek+r/w,目标:减少seek时间。
应用缓存->系统缓存->物理硬盘。
1,流式io:buf,如fwrite。用户层程序crash时的数据一致性问题。
2,底层io:如write。OS crash。
3,直接io:direct io。机器crash。

分布式存储系统:性能,数据备份。对事务支持困难。

三,网络io
实时性vs并发性。
同步模型:io和逻辑皆同步,epoll句柄池中取句柄(可读/写)->线程同步处理。有可能被r/w阻塞。
半同步半异步模型:折中选择,句柄池中取句柄(读/写完毕,数据ready)->线程同步处理。时效性稍差(数据ready,处理逻辑不足)
全异步模型模型:高性能,避免网络r/w io和磁盘io,io状态机。不提供同步语义。举例:
3级流水线框架:网络,CPU,磁盘。每级多个并发处理单元。
目标:避免某级空等。需要合理调度。

几个小tips:
1,长连接性能优于短链接。
2,留意短链接时的timewait。
3,不连续内存读写:readv,writev,节省内存cp。
4,同台机器,使用domain socket避免流量过网卡:如2个交互程序部署在一台机器上,原理:shm。

Tagged with: ,