一、环境

系统        CentOS6.4x64最小化安装

redis-m      192.168.1.13

二、安装redis

下载软件

[root@redis-m ~]# wget http://download.redis.io/releases/redis-2.8.9.tar.gz

安装

[root@redis-m ~]# tar xf redis-2.8.9.tar.gz 
[root@redis-m ~]# cd redis-2.8.9
[root@redis-m redis-2.8.9]# make
[root@redis-m redis-2.8.9]# make PREFIX=/usr/local/redis-2.8.9 install
[root@redis-m redis-2.8.9]# ln -s /usr/local/redis-2.8.9/ /usr/local/redis

#默认文件
[root@redis-m ~]# ll /usr/local/redis/bin
total 13912
-rwxr-xr-x 1 root root 4172184 Jul 26 18:08 redis-benchmark    #redis性能测试工具
-rwxr-xr-x 1 root root   22177 Jul 26 18:08 redis-check-aof    #对更新日志appendonly.aof检查,是否可用
-rwxr-xr-x 1 root root   45411 Jul 26 18:08 redis-check-dump    #用于本地数据库rdb文件的检查
-rwxr-xr-x 1 root root 4265375 Jul 26 18:08 redis-cli           #redis命令行操作工具
-rwxr-xr-x 1 root root 5728711 Jul 26 18:08 redis-server        #服务器的daemon启动程序

启动redis

#增加环境变量
[root@redis-m ~]# echo 'PATH=$PATH:/usr/local/redis/bin' >>/etc/profile
[root@redis-m ~]# source /etc/profile
[root@redis-m ~]# which redis-server
/usr/local/redis/bin/redis-server

[root@redis-m ~]# redis-server -h
Usage: ./redis-server [/path/to/redis.conf] [options]
       ./redis-server - (read config from stdin)
       ./redis-server -v or --version
       ./redis-server -h or --help
       ./redis-server --test-memory <megabytes>

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
       
#启动服务,由于默认是没有配置文件,所以我们从安装目录cp一个配置文件
[root@redis-m ~]# mkdir /usr/local/redis/conf
[root@redis-m ~]# cp /root/redis-2.8.9/redis.conf /usr/local/redis/conf/

#在后台启动
[root@redis-m ~]# redis-server /usr/local/redis/conf/redis.conf &
[1] 5870
[root@redis-m ~]# [5870] 26 Jul 18:24:24.771 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 2.8.9 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in stand alone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 5870
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

[5870] 26 Jul 18:24:24.774 # Server started, Redis version 2.8.9
[5870] 26 Jul 18:24:24.774 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[5870] 26 Jul 18:24:24.774 * The server is now ready to accept connections on port 6379

[root@redis-m ~]# netstat -tunlp |grep redis
tcp        0      0 0.0.0.0:6379                0.0.0.0:*                   LISTEN      5870/redis-server * 
tcp        0      0 :::6379                     :::*                        LISTEN      5870/redis-server *

#解决warning警告
[root@redis-m ~]# sysctl vm.overcommit_memory=1
vm.overcommit_memory = 1
[root@redis-m ~]# echo "vm.overcommit_memory = 1" >>/etc/sysctl.conf
[root@redis-m ~]# sysctl -p

#关闭redis服务
[root@redis-m ~]# redis-cli shutdown
[5870] 26 Jul 18:32:13.908 # User requested shutdown...
[5870] 26 Jul 18:32:13.908 * Saving the final RDB snapshot before exiting.
[5870] 26 Jul 18:32:13.926 * DB saved on disk
[5870] 26 Jul 18:32:13.926 # Redis is now ready to exit, bye bye...
[1]+  Done                    redis-server /usr/local/redis/conf/redis.conf
[root@redis-m ~]# netstat -tunlp |grep redis

redis启动脚本

[root@redis-m ~]# cat redis.sh
#!/bin/bash
# chkconfig: 2345 50 30
#
# description: Redis service
#
#Script:Redis command
 
Redisserver=/usr/local/redis/bin/redis-server
Rediscli=/usr/local/redis/bin/redis-cli
Redisconf=/usr/local/redis/conf/redis.conf
 
function_start()
{
	printf "start redis-server..."
	$Redisserver $Redisconf &>/dev/null  & 
	if [ $? -eq 0 ];then
		echo "runing"
	fi
}
 
function_stop()
{
	printf "stop redis-server..."
	$Rediscli -p 6379 shutdown
	if [ $? -eq 0 ];then
		echo "stop"
	fi
}
 
function_restart()
{
	function_start
	function_stop
}
 
function_kill()
{
	killall redis-server
}
 
function_status()
{
	a=`ps -A|grep "redis-server\>" -c`
	if [ $a -ge 1 ];then
		echo -e "The Redis is [\e[0;32;5m runing \e[0m]"
	else
		echo -e "The Redis is [\e[0;31;5m not run \e[0m]"
	fi
}
 
case "$1" in
        start)
                function_start
                ;;
        stop)
                function_stop
                ;;
        restart)
                function_stop
                function_start
                ;;
        kill)
                function_kill
                ;;
        status)
                function_status
                ;;
              *)
              echo "Usage: /etc/init.d/redis {start|stop|restart|kill|status}"
             
esac
 
exit

三、操作redis

[root@redis-m ~]# redis-cli 
#添加一个值set  key value
127.0.0.1:6379> set id 001
OK
127.0.0.1:6379> get id
"001"
127.0.0.1:6379> del id
(integer) 1        #返回1,表示操作成功
127.0.0.1:6379> get id
(nil)
127.0.0.1:6379> exists id        #判断一个key是否存在
(integer) 0        #返回0表示不存在

#切换数据库,默认有16个库,标号从0-15,这里我们切换到1号库
127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
(empty list or set)
127.0.0.1:6379[1]> set name lyao
OK
127.0.0.1:6379[1]> get name
"lyao"

#切回0号库
127.0.0.1:6379[1]> select 0
OK
127.0.0.1:6379> get name        #这个key只在1号库中才有
(nil)

#其它的连接方法
[root@redis-m ~]# redis-cli  -h 192.168.1.13 -p 6379
192.168.1.13:6379> 
-h    #指定主机地址
-p    #指定端口号

#redis使用帮助
[root@redis-m ~]# redis-cli 
127.0.0.1:6379> help
redis-cli 2.8.9
Type: "help @<group>" to get a list of commands in <group>
      "help <command>" for help on <command>
      "help <tab>" to get a list of possible help topics
      "quit" to exit
127.0.0.1:6379> help set        #查询某个命令的使用帮助

  SET key value [EX seconds] [PX milliseconds] [NX|XX]
  summary: Set the string value of a key
  since: 1.0.0
  group: string
  
#查询某类命令
127.0.0.1:6379> help @string

  APPEND key value
  summary: Append a value to a key
  since: 2.0.0

  BITCOUNT key [start] [end]
  summary: Count set bits in a string
  since: 2.6.0

  BITOP operation destkey key [key ...]
  summary: Perform bitwise operations between strings
  since: 2.6.0

  DECR key
  summary: Decrement the integer value of a key by one
  since: 1.0.0

  DECRBY key decrement
  summary: Decrement the integer value of a key by the given number
  since: 1.0.0

  GET key
  summary: Get the value of a key
  since: 1.0.0

  GETBIT key offset
  summary: Returns the bit value at offset in the string value stored at key
  since: 2.2.0

  GETRANGE key start end
  summary: Get a substring of the string stored at a key
  since: 2.4.0

  GETSET key value
  summary: Set the string value of a key and return its old value
  since: 1.0.0

  INCR key
  summary: Increment the integer value of a key by one
  since: 1.0.0

  INCRBY key increment
  summary: Increment the integer value of a key by the given amount
  since: 1.0.0

  INCRBYFLOAT key increment
  summary: Increment the float value of a key by the given amount
  since: 2.6.0

  MGET key [key ...]
  summary: Get the values of all the given keys
  since: 1.0.0

  MSET key value [key value ...]
  summary: Set multiple keys to multiple values
  since: 1.0.1

  MSETNX key value [key value ...]
  summary: Set multiple keys to multiple values, only if none of the keys exist
  since: 1.0.1

  PSETEX key milliseconds value
  summary: Set the value and expiration in milliseconds of a key
  since: 2.6.0

  SET key value [EX seconds] [PX milliseconds] [NX|XX]
  summary: Set the string value of a key
  since: 1.0.0

  SETBIT key offset value
  summary: Sets or clears the bit at offset in the string value stored at key
  since: 2.2.0

  SETEX key seconds value
  summary: Set the value and expiration of a key
  since: 2.0.0

  SETNX key value
  summary: Set the value of a key, only if the key does not exist
  since: 1.0.0

  SETRANGE key offset value
  summary: Overwrite part of a string at key starting at the specified offset
  since: 2.2.0

  STRLEN key
  summary: Get the length of the value stored in a key
  since: 2.2.0

四、redis权限

redis为客户端设置外部连接密码

[root@redis-m ~]# vim /usr/local/redis/conf/redis.conf
requirepass lyao36843    #相关说明大概在326行,每秒能进行150k次数的密码尝试

#重启redis服务
[root@redis-m ~]# redis-cli shutdown
[5892] 26 Jul 19:49:03.756 # User requested shutdown...
[5892] 26 Jul 19:49:03.756 * Saving the final RDB snapshot before exiting.
[5892] 26 Jul 19:49:03.789 * DB saved on disk
[5892] 26 Jul 19:49:03.789 # Redis is now ready to exit, bye bye...
[1]+  Done                    redis-server /usr/local/redis/conf/redis.conf
[root@redis-m ~]# redis-server /usr/local/redis/conf/redis.conf &
[root@redis-m ~]# redis-cli 
127.0.0.1:6379> set k v
(error) NOAUTH Authentication required.        #提示权限不够

#设置密码后,在进行命令操作之前,需要进行auth认证
127.0.0.1:6379> auth lyao36843
OK
127.0.0.1:6379> set k v
OK
127.0.0.1:6379> get k
"v"                            #能够正常增加值

#另外一种连接方式
[root@redis-m ~]# redis-cli -a lyao36843
127.0.0.1:6379> set k1 v1
OK
127.0.0.1:6379> get k1
"v1"

五、redis数据类型

数据类型有string,list,set,hash这几种

string类型

127.0.0.1:6379> set mykey "my binary safe value"
OK
127.0.0.1:6379> get mykey
"my binary safe value"

#用来计数
127.0.0.1:6379> set counter 1
OK
127.0.0.1:6379> incr counter        #自增
(integer) 2
127.0.0.1:6379> incr counter
(integer) 3
127.0.0.1:6379> incr counter
(integer) 4
127.0.0.1:6379> decr counter        #自减
(integer) 3
127.0.0.1:6379> decr counter
(integer) 2

#getset用法
127.0.0.1:6379> set name lyao
OK
127.0.0.1:6379> getset name lyao36843    #先获取name的值,然后将name的值更新为lyao36843
"lyao"
127.0.0.1:6379> get name
"lyao36843"

#批量操作
127.0.0.1:6379> mset name1 tom age 26 sex male
OK
127.0.0.1:6379> mget name1 age sex
1) "tom"
2) "26"
3) "male"

#给值追加内容
127.0.0.1:6379> get name1
"tom"
127.0.0.1:6379> append name1 "teacher"
(integer) 10
127.0.0.1:6379> get name1
"tomteacher"

六、redis多实例

[root@redis-m ~]# mkdir -p /data/6380/data
[root@redis-m ~]# mkdir -p /data/6381/data
[root@redis-m ~]# cp /usr/local/redis/conf/redis.conf /data/6380
[root@redis-m ~]# cp /usr/local/redis/conf/redis.conf /data/6381

#编辑6380的配置文件
[root@redis-m ~]# vim /data/6380/redis.conf
dir /data/6380/data                #修改dump文件的数据目录
port 6380                          #修改端口号
pidfile /data/6380/redis.pid       #修改pid文件路径

#编辑6381的配置文件
[root@redis-m ~]# vim /data/6381/redis.conf 
pidfile /data/6381/redis.pid
port 6381
dir /data/6381/data

#启动多实例
[root@redis-m ~]# redis-server /data/6380/redis.conf &
[root@redis-m ~]# redis-server /data/6381/redis.conf &

#查看端口
[root@redis-m ~]# netstat -tunlp | grep redis
tcp        0      0 0.0.0.0:6379                0.0.0.0:*                   LISTEN      5956/redis-server * 
tcp        0      0 0.0.0.0:6380                0.0.0.0:*                   LISTEN      6156/redis-server * 
tcp        0      0 0.0.0.0:6381                0.0.0.0:*                   LISTEN      6161/redis-server * 
tcp        0      0 :::6379                     :::*                        LISTEN      5956/redis-server * 
tcp        0      0 :::6380                     :::*                        LISTEN      6156/redis-server * 
tcp        0      0 :::6381                     :::*                        LISTEN      6161/redis-server * 
#从上面结果我们能看到,6379,6380,6381这3个redis实例都正常运行起来了

#连接到6380实例
[root@redis-m ~]# redis-cli -p 6380
127.0.0.1:6380> auth lyao36843
OK
127.0.0.1:6380> set name k1
OK
127.0.0.1:6380> get name
"k1"
127.0.0.1:6380> quit

#连接到6381实例
[root@redis-m ~]# redis-cli -p 6381
127.0.0.1:6381> auth lyao36843
OK
127.0.0.1:6381> set web httpd
OK
127.0.0.1:6381> get web
"httpd"
127.0.0.1:6381> quit

七、主从配置

主从同步基本原理如下

1.slave服务器连接到master服务器

2.slave服务器发送sync命令

3.master备份数据到.rdb文件

4.master把.rdb文件传输给slave服务器

5.slave把.rdb文件导入到数据库中

下面的主从配置,我们使用2个redis实例进行

#启动6379,6380配置
[root@redis-m ~]# netstat -tunlp |grep redis
tcp        0      0 0.0.0.0:6379                0.0.0.0:*                   LISTEN      1634/redis-server * 
tcp        0      0 0.0.0.0:6380                0.0.0.0:*                   LISTEN      1647/redis-server * 
tcp        0      0 :::6379                     :::*                        LISTEN      1634/redis-server * 
tcp        0      0 :::6380                     :::*                        LISTEN      1647/redis-server * 

#我们以6379作为主,6380作为主,编辑6380的配置文件
[root@redis-m ~]# vim /data/6380/redis.conf
slaveof 192.168.1.13  6379        #指定master的IP和端口信息
masterauth <master-password>        #这一项是设置master的密码的,我们没有密码所有没有进行设置

#重启6380的redis服务
[root@redis-m ~]# redis-cli -p 6380 shutdown
[1647] 28 Jul 14:25:48.209 # User requested shutdown...
[1647] 28 Jul 14:25:48.210 * Saving the final RDB snapshot before exiting.
[1647] 28 Jul 14:25:48.223 * DB saved on disk
[1647] 28 Jul 14:25:48.225 # Redis is now ready to exit, bye bye...
[root@redis-m ~]# netstat -tunlp |grep redis
tcp        0      0 0.0.0.0:6379                0.0.0.0:*                   LISTEN      1634/redis-server * 
tcp        0      0 :::6379                     :::*                        LISTEN      1634/redis-server * 
[root@redis-m ~]# redis-server /data/6380/redis.conf &
[2] 1676
[root@redis-m ~]# [1676] 28 Jul 14:26:40.304 * Increased maximum number of open files to 10032 (it was originally set to 1024).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 2.8.9 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in stand alone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6380
 |    `-._   `._    /     _.-'    |     PID: 1676
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               

[1676] 28 Jul 14:26:40.307 # Server started, Redis version 2.8.9
[1676] 28 Jul 14:26:40.308 * DB loaded from disk: 0.000 seconds
[1676] 28 Jul 14:26:40.308 * The server is now ready to accept connections on port 6380
[1676] 28 Jul 14:26:41.308 * Connecting to MASTER 192.168.1.13:6379
[1676] 28 Jul 14:26:41.308 * MASTER <-> SLAVE sync started
[1676] 28 Jul 14:26:41.308 * Non blocking connect for SYNC fired the event.
[1676] 28 Jul 14:26:41.308 * Master replied to PING, replication can continue...
[1676] 28 Jul 14:26:41.308 * Partial resynchronization not possible (no cached master)
[1634] 28 Jul 14:26:41.308 * Slave asks for synchronization
[1634] 28 Jul 14:26:41.308 * Full resync requested by slave.
[1634] 28 Jul 14:26:41.308 * Starting BGSAVE for SYNC
[1676] 28 Jul 14:26:41.310 * Full resync from master: 5e26f07d111a362449cd1fecfc4d720019e66339:1
[1634] 28 Jul 14:26:41.318 * Background saving started by pid 1679
[1679] 28 Jul 14:26:41.349 * DB saved on disk
[1679] 28 Jul 14:26:41.350 * RDB: 6 MB of memory used by copy-on-write
[1634] 28 Jul 14:26:41.367 * Background saving terminated with success
[1634] 28 Jul 14:26:41.368 * Synchronization with slave succeeded
#下面是主从建立后的同步信息
[1676] 28 Jul 14:26:41.368 * MASTER <-> SLAVE sync: receiving 150 bytes from master
[1676] 28 Jul 14:26:41.368 * MASTER <-> SLAVE sync: Flushing old data
[1676] 28 Jul 14:26:41.368 * MASTER <-> SLAVE sync: Loading DB in memory
[1676] 28 Jul 14:26:41.368 * MASTER <-> SLAVE sync: Finished with success

#测试连接到主redis上
[root@redis-m ~]# redis-cli -p 6379
127.0.0.1:6379> set docker kvm        #增加一个key为docker,值为kvm
OK
127.0.0.1:6379> get docker
"kvm"

#在从redis上查看结果
[root@redis-m ~]# redis-cli -p 6380
127.0.0.1:6380> get docker             #从库已经将数据同步过来,在从库上能正常查询到结果
"kvm"

#在redis的主从结构中slave是不能写数据的
127.0.0.1:6380> set ldap lyao
(error) READONLY You can't write against a read only slave.    #提示slave是只读的

#查看slave的replication信息
[root@redis-m ~]# redis-cli -p 6380 info replication
# Replication
role:slave
master_host:192.168.1.13
master_port:6379
master_link_status:up
master_last_io_seconds_ago:5
master_sync_in_progress:0
slave_repl_offset:2004
slave_priority:100
slave_read_only:1
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

#查看master的replication的信息
[root@redis-m ~]# redis-cli -p 6379 info replication
# Replication
role:master
connected_slaves:1
slave0:ip=192.168.1.13,port=6380,state=online,offset=2074,lag=1
master_repl_offset:2074
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:2
repl_backlog_histlen:2073

八、redis设置key过期时间

[root@redis-m ~]# redis-cli -p 6379
127.0.0.1:6379> keys *
 1) "age"
 2) "counter"
 3) "sex"
 4) "mykey"
 5) "k1"
 6) "name"
 7) "docker"
 8) "name1"
 9) "anme1"
10) "k"
127.0.0.1:6379> flushdb        #删除当前库所有数据
OK
127.0.0.1:6379> keys *
(empty list or set)

#重新设置一个key为name,值为lyao
127.0.0.1:6379> set name lyao
OK
127.0.0.1:6379> ttl name
(integer) -1                    #-1表示永不过期
127.0.0.1:6379> expire name 10        #设置key的过期时间是10s
(integer) 1
127.0.0.1:6379> ttl name
(integer) 8
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> ttl name
(integer) -2
127.0.0.1:6379> get name            #key已经过期
(nil)