CentOS 6.5下Redis安装部署配置指南
CentOS6.5下redis安装部署配置指南、常用命令、主从同步集群、redis-php学习资料整合详解。
1、Redis的介绍、安装、配置、启动流程 1.1、Redis 特征简介 Redis是Remote Dictionary Server的缩写。他本质上一个Key/Value数据库,与Memcached类似的NoSQL型数据库,但是他的数据可以持久化的保存在磁盘上,解决了服务重启后数据不丢失的问题,他的值可以是string(字符串)、list(列表)、sets(集合)或者是ordered sets(被排序的集合),所有的数据类型都具有push/pop、add/remove、执行服务端的并集、交集、两个sets集中的差别等等操作,这些操作都是具有原子性的,Redis还支持各种不同的排序能力。
Redis 支持绝大部分主流的开发语言, 如: PHP、 Java、 C#、 Perl、 Python、 Ruby 等等 通常,Redis将数据存储于内存中,或被配置为使用虚拟内存。通过两种方式可以实现数据持久化:使用截图的方式,将内存中的数据不断写入磁盘;或使用类似 MySQL 的日志方式,记录每次更新的日志。前者性能较高,但是可能会引起一定程度的数据丢失;后者相反。
Redis 支持将数据同步到多台从库上,这种特性对提高读取性能非常有(在物理机真实环境中每秒高并发读取速度能达到十万多次)。
1.2、redis下载 # wget http://download.redis.io/releases/redis-3.0.5.tar.gz 1.3、解压 # tar xf redis-3.0.5.tar.gz 这样就在当前目录下新建了一个包含发行版源代码的目录,必须cd进入这个目录以继续服务器的编译。
1.4、编译及安装
进入redis解压目录,执行如下命令编译Redis: # cd redis-3.0.5
make && make install
也可以指定目录安装: make prefix=/path/to/installdir install 安装tcmalloc包需指定参数,如make USE_TCMALLOC=yes FORCE_LIBC_MALLOC=yes 因为对一个基本的配置的编译,一般需要1分钟左右的时间,实际需要的时间因你的硬件和选择的模块数量会有很大不同。
1.5、配置
接着,复制redis.conf到/etc/下,修改配置文件,来配置Redis服务器。
1 # cp redis.conf /etc/
1.6、参数参看
1234567891011121314 # redis-server --help
Usage: ./redis-server
./redis-server - (read config from stdin)
./redis-server -v or --version
./redis-server -h or --help
./redis-server --test-memory
Examples:
./redis-server (run the server with default conf)
./redis-server /etc/redis/6379.conf
./redis-server --port 7777
./redis-server --port 7777 --slaveof 127.0.0.1 8888
./redis-server /etc/myredis.conf --loglevel verbose
Sentinel mode:
./redis-server /etc/sentinel.conf --sentinel
1.7、版本参看
redis-server -v
Redis server v=3.0.5 sha=00000000:0 malloc=jemalloc-3.6.0 bits=64 build=ee8d4e51452e5879
1.8、启动Redis服务器
# redis-server /etc/redis.conf
注:此命令仅有一个启动参数,指定/path/to/redis.conf目录下的配置文件,不加参数执行默认配置。
# redis-cli ping
PONG
测试启动 redis-cli ping 返回PONG,启动成功。
netstat -tulnp | grep 6379
tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 11731/redis-server
tcp 0 0 :::6379 :::* LISTEN 11731/redis-server
1.9、停止Redis 关闭服务
redis-cli shutdown
netstat -tulnp | grep 6379
redis-cli ping
Could not connect to Redis at 127.0.0.1:6379: Connection refused
注:可指定端口:redis-cli -p shutdown
1.10、连接Redis 两种链接redis的方法: 方法一、
redis-cli #也可以指定ip,端口号启动redis(redis-cli -h 192.168.1.2 -p 6379)
127.0.0.1:6379>
127.0.0.1:6379> quit
方法二、
telnet 192.168.1.2 6379
Trying 192.168.1.2... Connected to 192.168.1.2. Escape character is '^]'. quit +OK Connection closed by foreign host
.
2、redis常用命令详解 2.1、redis编译安装命令查看 #cd /usr/local/bin
ll | grep redis
-rwxr-xr-x. 1 root root 4587299 Nov 2 01:26 redis-benchmark -rwxr-xr-x. 1 root root 22177 Nov 2 01:26 redis-check-aof -rwxr-xr-x. 1 root root 45387 Nov 2 01:26 redis-check-dump -rwxr-xr-x. 1 root root 4691450 Nov 2 01:26 redis-cli lrwxrwxrwx. 1 root root 12 Nov 2 01:26 redis-sentinel -> redis-server -rwxr-xr-x. 1 root root 6464789 Nov 2 01:26 redis-server
2.2、redis-benchmark是Redis性能测试工具,测试Redis在你的系统及你的配置下的读写性能,redis的基准信息和性能检测。 redis-benchmark参数:
redis-benchmark --help
Usage: redis-benchmark >
-h Server hostname (default 127.0.0.1)
设置检测主机IP地址,默认为127.0.0.1
-p Server port (default 6379)
设置检测主机的端口号,默认为6379
-s Server socket (overrides host and port)
服务器套接字(压到主机和端口)
-a Password for Redis Auth
-c Number of parallel connections (default 50)
客户端并发连接数
-n Total number of requests (default 100000)
客户端总共发出的请求数
-d Data size of SET/GET value in bytes (default 2)
测试使用的数据集的大小/字节的值(默认2字节)
-dbnum SELECT the specified db number (default 0)
-k 1=keep alive 0=reconnect (default 1)
1:表示保持连接(默认值)0:重新连接
-r Use random keys for SET/GET/INCR, random values for SADD
Using this option the benchmark will expand the string rand_int
inside an argument with a 12 digits number in the specified range
from 0 to keyspacelen-1. The substitution changes every time a command
is executed. Default tests use this to hit random keys in the
specified range.
SET/GET/INCR方法使用随机数插入数值,如果设置为100则插入值为rand:000000000000 - rand:000000000099
-P Pipeline requests. Default 1 (no pipeline).
默认为1(无管道),当网络延迟过长时,使用管道方式通信(请求和响应打包发送接收)
-q Quiet. Just show query/sec values
简约信息模式,只显示查询和秒值等基本信息。
--csv Output in CSV format
以CSV格式输出信息
-l Loop. Run the tests forever
无线循环插入测试数据,ctrl+c停止
-t Only run the comma separated list of tests. The test
names are the same as the ones produced as output.
只运行测试逗号分隔的列表命令,如:-t ping,set,get
-I Idle mode. Just open N idle connections and wait.
空闲模式。立即打开50个空闲连接和等待。
Examples:
Run the benchmark with the default configuration against 127.0.0.1:6379:
$ redis-benchmark
Use 20 parallel clients, for a total of 100k requests, against 192.168.1.1:
$ redis-benchmark -h 192.168.1.1 -p 6379 -n 100000 -c 20
Fill 127.0.0.1:6379 with about 1 million keys only using the SET test:
$ redis-benchmark -t set -n 1000000 -r 100000000
Benchmark 127.0.0.1:6379 for a few commands producing CSV output:
$ redis-benchmark -t ping,set,get -n 100000 --csv
Benchmark a specific command line:
$ redis-benchmark -r 10000 -n 10000 eval 'return redis.call("ping")' 0
Fill a list with 10000 random elements:
$ redis-benchmark -r 10000 -n 10000 lpush mylist rand_int
On user specified command lines rand_int is replaced with a random integer
with a range of values selected by the -r option.
2.3、redis-cli 的使用说明 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 root@mysqldb1 ~]# redis-cli --help redis-cli 3.0.5 Usage: redis-cli ]] -h Server hostname (default: 127.0.0.1). -p Server port (default: 6379). -s Server socket (overrides hostname and port). -a Password to use when connecting to the server. -r Execute specified command N times. -i When -r is used, waits seconds per command. It is possible to specify sub-second times like -i 0.1. -n Database number. -x Read last argument from STDIN. -d Multi-bulk delimiter in for raw formatting (default: \n). -c Enable cluster mode (follow -ASK and -MOVED redirections). --raw Use raw formatting for replies (default when STDOUT is not a tty). --no-raw Force formatted output even when STDOUT is not a tty. --csv Output in CSV format. --stat Print rolling stats about server: mem, clients, ... --latency Enter a special mode continuously sampling latency. --latency-history Like --latency but tracking latency changes over time. Default time interval is 15 sec. Change it using -i. --latency-dist Shows latency as a spectrum, requires xterm 256 colors. Default time interval is 1 sec. Change it using -i. --lru-test Simulate a cache workload with an 80-20 distribution. --slave Simulate a slave showing commands received from the master. --rdb Transfer an RDB dump from remote server to local file. --pipe Transfer raw Redis protocol from stdin to server. --pipe-timeout In --pipe mode, abort with error if after sending all data. no reply is received within seconds. Default timeout: 30. Use 0 to wait forever. --bigkeys Sample Redis keys looking for big keys. --scan List all keys using the SCAN command. --pattern Useful with --scan to specify a SCAN pattern. --intrinsic-latency Run a test to measure intrinsic system latency. The test will run for the specified amount of seconds. --eval Send an EVAL command using the Lua script at . --help Output this help and exit. --version Output version and exit. Examples: cat /etc/passwd | redis-cli -x set mypasswd redis-cli get mypasswd redis-cli -r 100 lpush mylist x redis-cli -r 100 -i 1 info | grep used_memory_human: redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3 redis-cli --scan --pattern ':12345' (Note: when using --eval the comma separates KEYS from ARGV items) When no command is given, redis-cli starts in interactive mode. Type "help" in interactive mode for information on available commands.
2.4、redis-check-aof
更新日志检查 ,加--fix参数为修复log文件 redis-check-aof appendonly.aof
2.5、 redis-check-dump
检查本地数据库文件 redis-check-dump dump.rdb
2.6、获取服务器的信息和统计
redis-cli -p 6379 info
Server
redis_version:3.0.5 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:ee8d4e51452e5879 redis_mode:standalone os:Linux 2.6.32-431.el6.x86_64 x86_64 arch_bits:64 multiplexing_api:epoll gcc_version:4.4.7 process_id:11760 run_id:51f2b7336fae3bf3e1e4a21d76aa71b02f1e9608 tcp_port:6379 uptime_in_seconds:10033 uptime_in_days:0 hz:10 lru_clock:3570034 config_file:/etc/redis.conf
Clients
connected_clients:1 client_longest_output_list:0 client_biggest_input_buf:0 blocked_clients:0
Memory
used_memory:188575024 used_memory_human:179.84M used_memory_rss:241483776 used_memory_peak:228770552 used_memory_peak_human:218.17M used_memory_lua:36864 mem_fragmentation_ratio:1.28 mem_allocator:jemalloc-3.6.0
Persistence
loading:0 rdb_changes_since_last_save:0 rdb_bgsave_in_progress:0 rdb_last_save_time:1446405599 rdb_last_bgsave_status:ok rdb_last_bgsave_time_sec:2 rdb_current_bgsave_time_sec:-1 aof_enabled:0 aof_rewrite_in_progress:0 aof_rewrite_scheduled:0 aof_last_rewrite_time_sec:-1 aof_current_rewrite_time_sec:-1 aof_last_bgrewrite_status:ok aof_last_write_status:ok
Stats
total_connections_received:71398 total_commands_processed:22036268 instantaneous_ops_per_sec:0 total_net_input_bytes:820805789 total_net_output_bytes:15461673777 instantaneous_input_kbps:0.00 instantaneous_output_kbps:0.00 rejected_connections:0 sync_full:0 sync_partial_ok:0 sync_partial_err:0 expired_keys:0 evicted_keys:0 keyspace_hits:6295156 keyspace_misses:0 pubsub_channels:0 pubsub_patterns:0 latest_fork_usec:3258 migrate_cached_sockets:0
Replication
role:master connected_slaves:0 master_repl_offset:0 repl_backlog_active:0 repl_backlog_size:1048576 repl_backlog_first_byte_offset:0 repl_backlog_histlen:0
CPU
used_cpu_sys:388.55 used_cpu_user:250.86 used_cpu_sys_children:1.06 used_cpu_user_children:3.15
Cluster
cluster_enabled:0
Keyspace
db0:keys=994967,expires=0,avg_ttl=0
3、redis主从模式实战
3.1、Redis的主从配置简介:
在Redis中配置Master-Slave模式其实非常的简单。相信在阅读完下面的文章您可以轻松愉快做到完成redis的Master-Slave同步。这里我先给大家列出一些理论性的知识,后面给出实际操作的案例。
下面的列表清楚的解释了Redis Replication的特点和优势。
1、同一个Master可以同步多个Slaves。 2、Slave同样可以接受其它Slaves的连接和同步请求,这样可以有效的分载Master的同步压力。因此我们可以将Redis的Replication架构视为图结构。
3、Master Server是以非阻塞的方式为Slaves提供服务。所以在Master-Slave同步期间,客户端仍然可以提交查询或修改请求。
4、Slave Server同样是以非阻塞的方式完成数据同步。在同步期间,如果有客户端提交查询请求,Redis则返回同步之前的数据。5、为了分担Master的读操作压力,Slave服务器可以为客户端提供只读操作的服务,写服务仍然必须由Master来完成。即便如此,系统的伸缩性还是得到了很大的提高。
6、Master可以将数据保存操作交给Slaves完成,从而避免了在Master中要有独立的进程来完成此操作。
3.2、redis主从的工作原理:
在Slave启动并连接到Master之后,它将主动发送一个SYNC命令。此后Master将启动后台存盘进程,同时收集所有接收到的用于修改数据集的命令,在后台进程执行完毕后,Master将传送整个数据库文件到Slave,以完成一次完全同步。而Slave服务器在接收到数据库文件数据之后将其存盘并加载到内存中。此后,Master继续将所有已经收集到的修改命令,和新的修改命令依次传送给Slaves,Slave将在本次执行这些数据修改命令,从而达到最终的数据同步。
如果Master和Slave之间的链接出现断连现象,Slave可以自动重连Master,但是在连接成功之后,一次完全同步将被自动执行。
3.3、配置步骤说明:
Redis 的 master/slave 数据复制方式可以是一主一从或者是一主多从的方式,Redis 在master 是非阻塞模式,也就是说在 slave 执行数据同步的时候,master 是可以接受客户端的请求的,并不影响同步数据的一致性,然而在 slave 端是阻塞模式的,slave 在同步 master数据时,并不能够响应客户端的查询Redis 的 master/slave 模式下,master 提供数据读写服务,而 slave 只提供读服务Redis的 master/slave 的配置方式是在 slave 主机的 Redis目录下的 redis.conf 配置文件中
配置方式可以有2种:
1234567 1、一主一从
master -> slave
2、一主多从
master -> slave -> slave -> slave
├--> slave -> slave
├─-> slave -> slave
└─-> slave -> slave
一个集群可以包含最多4096个节点(主节点master和从节点slave),建议最多设置几百个节点,其配置特简单,就是把从服务器的redis.conf配置文件中的slaveof参数指向主服务器的ip 及 端口。
3.4、创建主从实现案例(本案例是通过一主机多端口的方式实现的):
3.4.1、创建redis主从目录
mkdir /redis/{master_6379,slave_6380}/{conf,log,data} -p
ls
master_6379 slave_6380
3.4.2、分别修改redis主从服务器的配置文件
cp /root/redis-3.0.5/redis.conf master_6379/conf/master.conf
cp /root/redis-3.0.5/redis.conf slave_6380/conf/slave.conf
vim master_6379/conf/master.conf#修改主服务器的配置文件
47 pidfile /redis/master_6379/redis_master.pid
51 port
110 logfile "/redis/master_6379/log/master.log"
193 dir /redis/master_6379/data/
515 appendfilename "appendonly.aof"
vim /redis/slave_6380/conf/slave.conf #修改从服务器的配置文件
46 pidfile /redis/slave_6380/redis_slave.pid 50 port 6380 109 logfile "/redis/slave_6380/log/slave.log" 192 dir /redis/slave_6380/data/ 212 slaveof 127.0.0.1 6379 514 appendfilename "appendonly.aof"
3.4.3、分别启动主、从服务器
redis-server /redis/master_6379/conf/master.conf
redis-server /redis/slave_6380/conf/slave.conf
3.4.4、分别查看主、从服务器的日志文件
cat /redis/master_6379/log/master.log #主服务器的日志文件
... ... 14363:M 02 Nov 12:42:57.805 * DB loaded from disk: 0.000 seconds 14363:M 02 Nov 12:42:57.805 * The server is now ready to accept connections on port 6379#主服务器的启动端口 14363:M 02 Nov 12:43:36.361 * Slave 127.0.0.1:6380 asks for synchronization#要求同步的从服务器信息 14363:M 02 Nov 12:43:36.361 * Full resync requested by slave 127.0.0.1:6380 14363:M 02 Nov 12:43:36.361 * Starting BGSAVE for SYNC with target: disk 14363:M 02 Nov 12:43:36.496 * Background saving started by pid 14371 14371:C 02 Nov 12:43:36.528 * DB saved on disk 14371:C 02 Nov 12:43:36.528 * RDB: 4 MB of memory used by copy-on-write 14363:M 02 Nov 12:43:36.597 * Background saving terminated with success 14363:M 02 Nov 12:43:36.597 * Synchronization with slave 127.0.0.1:6380 succeeded
cat /redis/slave_6380/log/slave.log #从服务器的日志文件
... ... 14368:S 02 Nov 12:43:35.424 * DB loaded from disk: 0.000 seconds 14368:S 02 Nov 12:43:35.424 * The server is now ready to accept connections on port 6380#从服务器的启动端口 14368:S 02 Nov 12:43:36.360 * Connecting to MASTER 127.0.0.1:6379#正在连接主服务器 14368:S 02 Nov 12:43:36.361 * MASTER <-> SLAVE sync started#主从同步已经开始 14368:S 02 Nov 12:43:36.361 * Non blocking connect for SYNC fired the event. 14368:S 02 Nov 12:43:36.361 * Master replied to PING, replication can continue... 14368:S 02 Nov 12:43:36.361 * Partial resynchronization not possible (no cached master) 14368:S 02 Nov 12:43:36.497 * Full resync from master: dd7a9d178eb3434494fecd4c97cc05e8d6bc1a69:1 14368:S 02 Nov 12:43:36.598 * MASTER <-> SLAVE sync: receiving 55 bytes from master 14368:S 02 Nov 12:43:36.598 * MASTER <-> SLAVE sync: Flushing old data 14368:S 02 Nov 12:43:36.598 * MASTER <-> SLAVE sync: Loading DB in memory 14368:S 02 Nov 12:43:36.598 * MASTER <-> SLAVE sync: Finished with success
3.4.5、查看redis主、从数据文件md5指纹信息
find /redis/ -name *.rdb | xargs md5sum
81646a7364950775039f694b1ddd6c8a /redis/slave_6380/data/slave_dump.rdb 81646a7364950775039f694b1ddd6c8a /redis/master_6379/data/master_dump.rdb
通过指纹信息可以得到redis主、从服务器的数据是一致的
3.4.6、向主服务器添加数据
redis-cli -p 6379
127.0.0.1:6379> set key1 hello OK 127.0.0.1:6379> set key2 liangge OK 127.0.0.1:6379> set key3 OK OK 127.0.0.1:6379> keys *
- "key2"
- "key1"
- "key3" 127.0.0.1:6379> quit
3.4.7、在从服务器上查看数据信息是否已同步
redis-cli -p 6380
127.0.0.1:6380> get key1 "hello" 127.0.0.1:6380> get key2 "liangge" 127.0.0.1:6380> get key3 "OK" 127.0.0.1:6380> keys *
- "key1"
- "key2"
- "key3" 127.0.0.1:6380> quit
3.4.8、再次查看主、从服务器的md5数据指纹
find /redis/ -name *.rdb |xargs md5sum
81646a7364950775039f694b1ddd6c8a /redis/slave_6380/data/slave_dump.rdb 81646a7364950775039f694b1ddd6c8a /redis/master_6379/data/master_dump.rdb
3.4.9、查看redis主从服务器工作目录
tree /redis
/redis ├── master_6379 │ ├── conf │ │ └── master.conf │ ├── data │ │ └── master_dump.rdb │ └── log │ └── master.log └── slave_6380 ├── conf │ └── slave.conf ├── data │ └── slave_dump.rdb └── log └── slave.log 8 directories, 6 files
4、PHP中安装redis插件
4.1、下载php_redis扩展模块 phpredis下载地址: https://codeload.github.com/owlient/phpredis/zip/master
4.2、安装php_redis扩展模块
unzip phpredis-master.zip
cd phpredis-master
/usr/local/php5.5.30/bin/phpize
./configure --with-php-config=/usr/local/php5.5.30/bin/php-config
make && make install
ll /usr/local/php5.5.30/lib/php/extensions/no-debug-non-zts-20121212/
total 1668 -rwxr-xr-x. 1 root root 465457 Nov 2 06:21 memcache.so -rwxr-xr-x. 1 root root 303946 Oct 14 04:24 opcache.a -rwxr-xr-x. 1 root root 210011 Oct 14 04:24 opcache.so -rwxr-xr-x. 1 root root 717996 Nov 2 18:35 redis.so #说明php_redis模块已经安装成功
4.3、在php.php文件中配置php_redis模块
12345 # vim /usr/local/php5.5.30/lib/php.ini
extension_dir="/usr/local/php5.5.30/lib/php/extensions/no-debug-non-zts-20121212/"
extension="memcache.so"
extension="redis.so"
#如果以前配置过php扩展模块现在只需要加上这行即可。
4.4、查看php是否启动,如果启动则重启,如若没有启动则直接启动。
netstat -tulnp | egrep "php|nginx"
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9922/nginx
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 13361/php-fpm
pkill php
netstat -tulnp | egrep "php|nginx"
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9922/nginx
/usr/local/php5.5.30/sbin/php-fpm -t
NOTICE: configuration file /usr/local/php5.5.30/etc/php-fpm.conf test is successful
/usr/local/php5.5.30/sbin/php-fpm -c /usr/local/php5.5.30/lib/php.ini
netstat -tulnp | egrep "php|nginx"
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9922/nginx
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 13400/php-fpm
4.5、在浏览器查看php_redis模块是否成功加载,本机是用linux命令行工具查看
curl localhost/phpinfo.php|grep redis
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0redis
5、编写php程序测试php_redis模块 5.1、php连接redis的程序代码
5.2、调试输出结果 after insert get mykey1: liangge after delete get mykey1:
下面关于Redis的文章您也可能喜欢,不妨参考下:
Ubuntu 14.04下Redis安装及简单测试 http://www.linuxidc.com/Linux/2014-05/101544.htm
Redis主从复制基本配置 http://www.linuxidc.com/Linux/2015-03/115610.htm
Redis集群明细文档 http://www.linuxidc.com/Linux/2013-09/90118.htm
Ubuntu 12.10下安装Redis(图文详解)+ Jedis连接Redis http://www.linuxidc.com/Linux/2013-06/85816.htm
Redis系列-安装部署维护篇 http://www.linuxidc.com/Linux/2012-12/75627.htm
CentOS 6.3安装Redis http://www.linuxidc.com/Linux/2012-12/75314.htm
Redis安装部署学习笔记 http://www.linuxidc.com/Linux/2014-07/104306.htm
Redis配置文件redis.conf 详解 http://www.linuxidc.com/Linux/2013-11/92524.htm
Redis 的详细介绍:请点这里 Redis 的下载地址:请点这里
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-03/129301.htm