准备工作
-
源码下载
各个版本的Redis源码可通过官网进行下载,地址为:http://download.redis.io/releases/。为了简化学习,我是下载了第一个版本的Redis源码
redis-0.100
。下载后解压到自己指定的目录。 -
源码编译
进入目录后执行
make
命令进行编译,结束后会生成三个可执行文件,redis服务程序redis-server
、redis客户端程序redis-cli
、redis基准(压力)测试程序redis-benchmark
。 -
运行服务端
命令行执行
./redis-server
,启动redis服务端程序。root@root:# ./redis-server 29 Jul 00:50:58 * WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. To fix this issue add 'echo 1 > /proc/sys/vm/overcommit_memory' in your init scripts. 29 Jul 00:50:58 * Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf' 29 Jul 00:50:58 - Server started, Redis version 0.100 29 Jul 00:50:58 - DB loaded from disk 29 Jul 00:50:58 - The server is now ready to accept connections on port 6379 29 Jul 00:50:59 . DB 0: 2 keys (0 volatile) in 16 slots HT. 29 Jul 00:50:59 . 0 clients connected (0 slaves), 4845 bytes in use 29 Jul 00:51:04 . DB 0: 2 keys (0 volatile) in 16 slots HT. 29 Jul 00:51:04 . 0 clients connected (0 slaves), 4845 bytes in use 29 Jul 00:51:09 . DB 0: 2 keys (0 volatile) in 16 slots HT. 29 Jul 00:51:09 . 0 clients connected (0 slaves), 4845 bytes in use
可以看到两个WARNING告警信息。
-
告警一:
WARNING overcommit_memory is set to 0! Background save may fail under low condition memory. To fix this issue add 'echo 1 > /proc/sys/vm/overcommit_memory' in your init scripts
告警:overcommit_memory被设置为0!在内存不足的情况下,后台保存可能会失败。为了解决这个问题,请在您的init脚本中添加“echo 1 > /proc/sys/vm/overcommit_memory”。
overcommit_memory:存分配策略,内核对内存分配的一种策略;控制分配内存是否可以超过CommitLimit,默认是0,即启发式的overcommitting handle,会尽量减少swap的使用,root可以分配比一般用户略多的内存。1表示允许超过CommitLimit,2表示不允许超过CommitLimit
- overcommit_memory=0, 表示内核将检查是否有足够的可用内存供应用进程使用;如果有足够 的可用内存,内存申请允许;否则,内存申请失败,并把错误返回给应用进程。
- overcommit_memory=1, 表示内核允许分配所有的物理内存,而不管当前的内存状态如何。
- overcommit_memory=2, 表示内核允许分配超过所有物理内存和交换空间总和的内存
Overcommit 和 OOM:Linux对大部分申请内存的请求都回复"yes",以便能跑更多更大的程序。因为申请内存后,并不会马上使用内存。这种技术叫做Overcommit。当linux发现内存不足时,会发生OOM killer(OOM=out-of-memory)。它会选择杀死一些进程(用户态进程,不是内核线程),以便释放内存。
当oom-killer发生时,linux会选择杀死哪些进程?选择进程的函数是oom_badness函数(在mm/oom_kill.c中),该函数会计算每个进程的点数(0~1000)。点数越高,这个进程越有可能被杀死。每个进程的点数跟oom_score_adj有关,而且oom_score_adj可以被设置(-1000最低,1000最高)。
解决方法:按照提示设置overcommit_memor为1即可。有三种方式可修改此参数:
- 编辑/etc/sysctl.conf ,改vm.overcommit_memory=1,然后sysctl -p 使配置文件生效
- sysctl vm.overcommit_memory=1
- echo 1 > /proc/sys/vm/overcommit_memory
-
告警二:
Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'
告警:未指定配置文件,将使用默认配置。如果要指定配置文件,请使用“redis-server /path/to/redis.conf”
解决方法:在启动Redis服务程序的时候加上redis的配置文件路径,如:
./redis-server /usr/local/src/redis-0.1/redis.conf
-
-
运行客户端
客户端有两种执行方式
-
指定连接ip与端口
./redis-cli -h 127.0.0.1 -p 6379 SET test-key test-val
-
使用默认ip与端口
./redis-cli SET test-key test-val
命令执行成功后会返回"OK"
-