1、Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。
2、安装
2.1 redis
下载源代码文件到/opt/oracle/soft/redis-3.0.1.tar.gz
解压tar -xzvfredis-3.0.1..tar.gz
进入目录cd redis-3.0.1
编译make
安装 make install
2.2 安装Ruby
下载源代码文件ruby-2.1.6.tar.gz
解压tar -xzvf ruby-2.1.6.tar.gz
进入目录cd ruby-2.1.6
运行 ./configure --prefix=/opt/oracle/ruby
编译make
安装 make install
配置环境变量
vi /etc/profile文件中增加
export PATH=/opt/oracle/ruby/bin:$PATH
执行source /etc/profile,使环境变量生效
验证ruby是否安装成功,执行ruby –v,出现如下输出,即ruby安装OK。
ruby 2.1.6p336 (2015-04-13 revision 50298) [x86_64-linux]
2.3 安装redis gem
下载源文件redis-3.2.1.gem
安装 gem install –l redis-3.2.1.gem
如果安装redis-3.2.1.gem出错,请执行如下步骤
安装zlib
tar -xzvf zlib-1.2.8.tar.gz
cd zlib-1.2.8
./configure --prefix=/opt/oracle/zlib
make
make install
2.4 安装ruby-zlib
cd ruby-2.1.6/ext/zlib
ruby ./extconf.rb --with-zlib-dir=/opt/oracle/zlib
make
make install
最后安装redis-3.2.1.gem
gem install -l redis-3.2.1.gem
3、配置
3.1 主备模式
master redis.conf
################################ GENERAL #####################################
daemonize yes
port 6379
logfile "/opt/oracle/redis/logs/Redis.log"
loglevel notice
syslog-enabled no
pidfile /opt/oracle/redis/logs/Redis.pid
dir "/opt/oracle/redis/data"
databases 1
################################ SNAPSHOTTING ################################
#save 900 1
#save 300 10
#save 60 10000
stop-writes-on-bgsave-error no
dbfilename "master.rdb"
rdbchecksum yes
################################# REPLICATION #################################
slave-serve-stale-data yes
slave-read-only yes
repl-backlog-size 1mb
repl-backlog-ttl 3600
min-slaves-to-write 0
min-slaves-max-lag 10
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
################################### LIMITS ####################################
maxclients 10000
tcp-backlog 128
maxmemory 1gb
maxmemory-policy noeviction
tcp-keepalive 60
lua-time-limit 5000
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
hz 10
aof-rewrite-incremental-fsync yes
############################## APPEND ONLY MODE ###############################
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
################################## SLOW LOG ###################################
slowlog-log-slower-than 10000
slowlog-max-len 128
slaver redis.conf
################################ GENERAL #####################################
daemonize yes
port 6380
logfile "/opt/oracle/redis/logs/SlaveRedis.log"
loglevel notice
syslog-enabled no
pidfile /opt/oracle/redis/logs/SlaveRedis.pid
dir "/opt/oracle/redis/data"
databases 1
################################ SNAPSHOTTING ################################
#save 900 1
#save 300 10
#save 60 10000
stop-writes-on-bgsave-error no
dbfilename "slave.rdb"
################################# REPLICATION #################################
slave-serve-stale-data yes
slave-read-only yes
repl-backlog-size 1mb
repl-backlog-ttl 3600
min-slaves-to-write 0
min-slaves-max-lag 10
slaveof 192.168.126.137 6379
################################### LIMITS ####################################
maxclients 10000
tcp-backlog 128
maxmemory 6gb
maxmemory-policy noeviction
tcp-keepalive 60
############################## APPEND ONLY MODE ###############################
appendonly no
################################## SLOW LOG ###################################
slowlog-log-slower-than 10000
slowlog-max-len 128
哨兵配置/opt/oracle/redis/sentinel.conf
sentinel monitor resque 192.168.14.207 6383 3
sentinel down-after-milliseconds resque 10000sentinel failover-timeout resque 180000sentinel parallel-syncs resque 5第一行配置指示 Sentinel 去监视一个名为 resque 的主服务器, 这个主服务器的 IP 地址为 192.168.14.207 , 端口号为 6383 , 而将这个主服务器判断为失效至少需要 3个 Sentinel 同意 (只要同意 Sentinel 的数量不达标,自动故障迁移就不会执行)。
不过要注意, 无论你设置要多少个 Sentinel 同意才能判断一个服务器失效, 一个 Sentinel 都需要获得系统中多数(majority) Sentinel 的支持, 才能发起一次自动故障迁移, 并预留一个给定的配置纪元 (configuration Epoch ,一个配置纪元就是一个新主服务器配置的版本号)。
换句话说, 在只有少数(minority) Sentinel 进程正常运作的情况下, Sentinel 是不能执行自动故障迁移的。
3.2 集群配置
master
################################ GENERAL #####################################
daemonize yes
port 6379
logfile "/opt/oracle/redis/logs/Redis.log"
loglevel notice
syslog-enabled no
pidfile /opt/oracle/redis/logs/Redis.pid
dir "/opt/oracle/redis/data"
databases 1
################################ SNAPSHOTTING ################################
#save 900 1
#save 300 10
#save 60 10000
stop-writes-on-bgsave-error no
dbfilename "master.rdb"
############################# CLUSTER #########################################
cluster-enabledyes
cluster-config-file/opt/oracle/redis/conf/masternodes.conf
cluster-node-timeout15000
cluster-migration-barrier1
cluster-require-full-coverageyes
################################# REPLICATION #################################
slave-serve-stale-data yes
slave-read-only yes
repl-backlog-size 1mb
repl-backlog-ttl 3600
min-slaves-to-write 0
min-slaves-max-lag 10
################################### LIMITS ####################################
maxclients 10000
tcp-backlog 128
maxmemory 6gb
maxmemory-policy noeviction
tcp-keepalive 60
############################## APPEND ONLY MODE ###############################
appendonly no
################################## SLOW LOG ###################################
slowlog-log-slower-than 10000
slowlog-max-len 128
slave
################################ GENERAL #####################################
daemonize yes
port 6380
logfile "/opt/oracle/redis/logs/SlaveRedis.log"
loglevel notice
syslog-enabled no
pidfile /opt/oracle/redis/logs/SlaveRedis.pid
dir "/opt/oracle/redis/data"
databases 1
################################ SNAPSHOTTING ################################
#save 900 1
#save 300 10
#save 60 10000
stop-writes-on-bgsave-error no
dbfilename "slave.rdb"
############################# CLUSTER #########################################
cluster-enabled yes
cluster-config-file /opt/oracle/redis/conf/slavenodes.conf
cluster-node-timeout 15000
cluster-migration-barrier 1
cluster-require-full-coverage yes
################################# REPLICATION #################################
slave-serve-stale-data yes
slave-read-only yes
repl-backlog-size 1mb
repl-backlog-ttl 3600
min-slaves-to-write 0
min-slaves-max-lag 10
################################### LIMITS ####################################
maxclients 10000
tcp-backlog 128
maxmemory 6gb
maxmemory-policy noeviction
tcp-keepalive 60
############################## APPEND ONLY MODE ###############################
appendonly no
################################## SLOW LOG ###################################
slowlog-log-slower-than 10000
slowlog-max-len 128
启动
redis启动:redis-server /opt/oracle/redis/redis.conf
哨兵启动:redis-sentinel /opt/oracle/redis/sentinel.conf
集群启动:
/opt/oracle/redis/bin/redis-trib.rb create --replicas 1 192.168.9.85:6379 192.168.9.86:6379 192.168.9.87:6379 192.168.9.88:6379 192.168.9.89:6379 192.168.9.85:6380 192.168.9.86:6380 192.168.9.87:6380 192.168.9.88:6380 192.168.9.89:6380
4、简单使用
a. 登陆缓存服务器。使用ssh工具登录到有redis客户端工具的服务器上。执行以下命令:
redis-cli [–h 127.0.0.1] [-p 6379] [--raw]
说明:以上[]内的内容可以省略。redis-cli 为redis客户端命令;-h为redis主机地址,-p为端口,--raw为字符串编码格式(需要显示中文时加上该参数,否者中文内容会显示为16进制数字)。
b. 查看redis中保存的key。
KEYS *:显示redis中所有的key,由于redis中存在着大量的key(可以使用DBSIZE命令查看当前redis中key的数量),所以不建议使用KEYS * 命令。可以使用匹配模式KEYS “MAM*“(显示Redis中所有以”MAM”开头的key)。
账户系统使用的key均以MAM开头,所以可以使用KEYS “MAM*“查看MAM所有缓存的key
c、TYPE key:查看key对应value的数据类型
redis> HMSET pet dog "doudou" cat "nounou" # 一次设置多个域
OKredis> HMGET pet dog cat fake_pet # 返回值的顺序和传入参数的顺序一样1) "doudou"2) "nounou"3) (nil) # 不存在的域返回nil值d、api
#!/usr/bin/python
#coding=utf-8
import time
import redis
from rediscluster import StrictRedisCluster
class CRedis:
def __init__(self):
self.startup_nodes = [{"host": "192.168.15.183", "port": "6379"},{"host": "192.168.15.183", "port": "6380"},{"host": "192.168.15.183", "port": "6381"},{"host": "192.168.15.175", "port": "6379"},{"host": "192.168.15.175", "port": "6380"},{"host": "192.168.15.175", "port": "6381"}]
self.r = StrictRedisCluster(startup_nodes=self.startup_nodes, decode_responses=True)
#1. strings 类型及操作
#设置 key 对应的值为 string 类型的 value
def set(self, key, value):
return self.r.set(key, value)
#设置 key 对应的值为 string 类型的 value。如果 key 已经存在,返回 0,nx 是 not exist 的意思
def setnx(self, key, value):
return self.r.setnx(key, value)
#设置 key 对应的值为 string 类型的 value,并指定此键值对应的有效期
def setex(self, key, time, value):
return self.r.setex(key, time, value)
#设置指定 key 的 value 值的子字符串
#setrange name 8 gmail.com
#其中的 8 是指从下标为 8(包含 8)的字符开始替换
def setrange(self, key, num, value):
return self.r.setrange(key, num, value)
#获取指定 key 的 value 值的子字符串
def getrange(self, key, start ,end):
return self.r.getrange(key, start, end)
#mget(list)
def get(self, key):
if isinstance(key, list):
return self.r.mget(key)
else:
return self.r.get(key)
#删除
def remove(self, key):
return self.r.delete(key)
#自增
def incr(self, key, default = 1):
if (1 == default):
return self.r.incr(key)
else:
return self.r.incr(key, default)
#自减
def decr(self, key, default = 1):
if (1 == default):
return self.r.decr(key)
else:
return self.r.decr(key, default)
#2. hashes 类型及操作
#根据email获取session信息
def hget(self, email):
return self.r.hget('session', email)
#以email作为唯一标识,增加用户session
def hset(self, email, content):
return self.r.hset('session', email, content)
#获取session哈希表中的所有数据
def hgetall(self):
return self.r.hgetall('session')
#删除hashes
def hdel(self, name, key = None):
if(key):
return self.r.hdel(name, key)
return self.r.hdel(name)
#清空当前db
def clear(self):
return self.r.flushdb()
#3、lists 类型及操作
#适合做邮件队列
#在 key 对应 list 的头部添加字符串元素
def lpush(self, key ,value):
return self.r.lpush(key, value)
#从 list 的尾部删除元素,并返回删除元素
def lpop(self, key):
return self.r.plush(key)
if __name__ == '__main__':
MessageProducer = CRedis()
count = 1
while True:
str = "it is %d queue"%(count)
MessageProducer.lpush("test",str)
count = count + 1
time.sleep(1)
consumer = CRedis()
queue = 'test'
timeout = 5
while True:
msg = consumer.brpop(queue, timeout)
if msg != None:
print msg