深刻浅出Redis05-Redis集群环境的配置

1、安装redis

1,下载redis最新版html

从如下redis地址下载最新版本的redis,使用使用redis-3.2.9.tar版本。java

http://download.redis.io/releases/

  这次,介绍安装redis的环境, 如下是安装环境的详细信息。node

Linux版本: CentOS 6.5
IP 地址 : 192.168.253.140

  查看Linux版本,IP地址的命令:python

cat /etc/issue
ifconfig

  为了安装Redis环境,须要进行必要的测试,首先须要关闭Linux的防火墙。c++

# 关闭命令:  
service iptables stop
# 永久关闭防火墙
chkconfig iptables off

  两个命令同时运行,运行完成后查看防火墙关闭状态redis

service iptables status

 2,须要gcc环境,若是没有执行命令安装gcc算法

yum install gcc-c++

3,下载redis3.0的源码包并上传至服务器centos

4,解压源码包缓存

tar -zxvf redis-3.0.0.tar.gz

5,进入解压目录编译ruby

make

6,安装redis

 make install PREFIX=/usr/local/redis

2、启动redis

1,从redis-3.0.0文件中复制redis-conf到redis的安装目录中
2,而后修改redis.conf文件

daemonize yes

3,在bin目录下启动redis

./bin/redis-server redis.conf

注意:redis默认占用端口是6379 。

4,中止redis服务

./bin/redis-cli shutdown

5, 链接到 redis服务器

 使用如下命令链接到redis远程服务器。

redis-cli -h 192.168.253.140 -p 6379

参数解释:

-h  远程redis服务器的IP地址。

-p  redis服务器对外开发的端口。

 

 遇到问题:

1,开启远程登陆链接。

从本地远程链接CentOS 服务器上的Redis,一直报错链接不成功。通过查询资料,发现原来redis默认只能localhost登录,因此须要开启远程登录。解决方法以下:

1)在redis的配置文件redis.conf中,找到bind对应的项,将bind 127.0.0.1 改为了bind 0.0.0.0 。表明着局域网内的全部计算机都能访问。

若是redis服务器启动了,先关闭它。

# 注释掉原有的bind项目
#bind 127.0.0.1

bind 0.0.0.0

band localhost   只能本机访问,局域网内计算机不能访问。
bind  局域网IP    只能局域网内IP的机器访问, 本地localhost都没法访问。
bind 0.0.0.0      表示本机和局域网内IP的机器都能访问。

2)从新启动redis服务,终于一切正常了,在本地链接上redis服务器后存储数据name ,能够在远程服务器正常显示。以下图所示:

 

3、redis集群的搭建

该集群中有三个节点,每一个节点有一主一备。本来须要6台虚拟机,可是为了节省资源,能够在一台虚拟机上启动6个redis实例。在此搭建一个伪分布式的集群,使用6个redis实例来模拟。向着目标前进吧,just do it 。

1,安装ruby环境

yum install ruby
yum install rubygems

使用如下命令安装ruby的redis的接口

gem install redis

若是返回如下错误信息,表示没法安装redis接口,由于没法链接到gem服务器。

须要手工下载并安装:

wget https://rubygems.global.ssl.fastly.net/gems/redis-3.2.1.gem
gem install -l ./redis-3.2.1.gem 

  还须要将redis集群管理工具redis-trib.rb上传至服务器。

2, 在/usr/local/redis目录下建立cluster目录

cd /usr/local/redis

mkdir cluster

 3,进入cluster目录,建立如下目录 7001,7002,7003,7004,7005,7006 。

cd /usr/local/redis/cluster
mkdir 7001
mkdir 7002
mkdir 7003
mkdir 7004
mkdir 7005
mkdir 7006

4,而后将/usr/local/redis/redis-3.*/redis.conf依次复制到7000 7002 7003 7004 7005 7006这6个目录

 能够参考如下命令完成操做。

cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7001
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7002
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7003
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7004
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7005
cp /usr/local/redis/redis.conf /usr/local/redis/cluster/7006

5,修改配置文件redis.conf

首先修改7001目录文件下的redis.conf配置文件

vi /usr/local/redis/cluster/7001/redis.conf

 修改配置文件中的下面选项

port 7001
daemonize yes
cluster-enabled yes
cluster-config-file nodes7001.conf
cluster-node-timeout 5000
appendonly yes

一样再对其它配置文件进行修改

vi /usr/local/redis/cluster/7002/redis.conf
vi /usr/local/redis/cluster/7003/redis.conf
vi /usr/local/redis/cluster/7004/redis.conf
vi /usr/local/redis/cluster/7005/redis.conf
vi /usr/local/redis/cluster/7006/redis.conf

注意:不一样的目录配置不一样的redis.conf中的port,cluster-config-file值。

 6,启动6个redis

cd /usr/local/redis
./bin/redis-server /usr/local/redis/cluster/7001/redis.conf
.
/bin/redis-server /usr/local/redis/cluster/7002/redis.conf
./bin/redis-server /usr/local/redis/cluster/7003/redis.conf
./bin/redis-server /usr/local/redis/cluster/7004/redis.conf
./bin/redis-server /usr/local/redis/cluster/7005/redis.conf
./bin/redis-server /usr/local/redis/cluster/7006/redis.conf

启动以后使用命令查看redis的启动状况 ps -ef|grep redis 

[root@localhost redis]# ps -ef | grep redis
root     17243     1  0 13:25 ?        00:00:00 ./bin/redis-server 0.0.0.0:7001 [cluster]                  
root     17248     1  0 13:25 ?        00:00:00 ./bin/redis-server 0.0.0.0:7002 [cluster]                  
root     17256     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7003 [cluster]                  
root     17260     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7004 [cluster]                  
root     17264     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7005 [cluster]                  
root     17268     1  0 13:26 ?        00:00:00 ./bin/redis-server 0.0.0.0:7006 [cluster]                  
root     17275 17149  0 13:27 pts/0    00:00:00 grep redis
[root@localhost redis]#

看到以上信息说明都启动成功。

7,建立redis集群

cd /usr/local/redis

./redis-trib.rb create --replicas 1 192.168.253.140:7001 192.168.253.140:7002 192.168.253.140:7003 192.168.253.140:7004 192.168.253.140:7005 192.168.253.140:7006

命令的意义以下:
  给定 redis-trib.rb 程序的命令是 create , 这表示咱们但愿建立一个新的集群。
  选项 --replicas 1 表示咱们但愿为集群中的每一个主节点建立一个从节点。
  以后跟着的其余参数则是实例的地址列表, 咱们但愿程序使用这些地址所指示的实例来建立新集群。
  简单来讲, 以上命令的意思就是让 redis-trib 程序建立一个包含三个主节点和三个从节点的集群。

   若是redis实例配置正常的话,返回以下信息,成功生成redis集群。注意:若是建立redis集群失败,只要把redis.conf中定义的 cluster-config-file 所在的文件删除,从新启动redis-server及运行redis-trib便可。

>>> Creating cluster
>>> Performing hash slots allocation on 6 nodes...
Using 3 masters:
127.0.0.1:7001
127.0.0.1:7002
127.0.0.1:7003
Adding replica 127.0.0.1:7004 to 127.0.0.1:7001
Adding replica 127.0.0.1:7005 to 127.0.0.1:7002
Adding replica 127.0.0.1:7006 to 127.0.0.1:7003
M: 98ce3e1be69335521e5928d82f7ea0214a751d2b 127.0.0.1:7001
   slots:0-5460 (5461 slots) master
M: f8856471eb35e874035d38c5bb54f2ff8987f665 127.0.0.1:7002
   slots:5461-10922 (5462 slots) master
M: 8ef8e2758c91327bc78f383e7303c0164fe47adb 127.0.0.1:7003
   slots:10923-16383 (5461 slots) master
S: 9a2ea466d8f3a4abac890ab752249e3eab0f4d74 127.0.0.1:7004
   replicates 98ce3e1be69335521e5928d82f7ea0214a751d2b
S: e960ae156a4942437ef9e4d6bc07b1b162eaa697 127.0.0.1:7005
   replicates f8856471eb35e874035d38c5bb54f2ff8987f665
S: 7a2046a101e338de2f78876b7798854e709a21fe 127.0.0.1:7006
   replicates 8ef8e2758c91327bc78f383e7303c0164fe47adb
Can I set the above configuration? (type 'yes' to accept): yes
>>> Nodes configuration updated
>>> Assign a different config epoch to each node
>>> Sending CLUSTER MEET messages to join the cluster
Waiting for the cluster to join....
>>> Performing Cluster Check (using node 127.0.0.1:7001)
M: 98ce3e1be69335521e5928d82f7ea0214a751d2b 127.0.0.1:7001
   slots:0-5460 (5461 slots) master
   1 additional replica(s)
S: e960ae156a4942437ef9e4d6bc07b1b162eaa697 127.0.0.1:7005
   slots: (0 slots) slave
   replicates f8856471eb35e874035d38c5bb54f2ff8987f665
S: 7a2046a101e338de2f78876b7798854e709a21fe 127.0.0.1:7006
   slots: (0 slots) slave
   replicates 8ef8e2758c91327bc78f383e7303c0164fe47adb
M: 8ef8e2758c91327bc78f383e7303c0164fe47adb 127.0.0.1:7003
   slots:10923-16383 (5461 slots) master
   1 additional replica(s)
M: f8856471eb35e874035d38c5bb54f2ff8987f665 127.0.0.1:7002
   slots:5461-10922 (5462 slots) master
   1 additional replica(s)
S: 9a2ea466d8f3a4abac890ab752249e3eab0f4d74 127.0.0.1:7004
   slots: (0 slots) slave
   replicates 98ce3e1be69335521e5928d82f7ea0214a751d2b
[OK] All nodes agree about slots configuration.
>>> Check for open slots...
>>> Check slots coverage...
[OK] All 16384 slots covered.
[root@localhost redis]# 

至此集群环境搭建成功了,遇到的问题终于解决了。: )

 

4、操做redis集群

1, 使用 redis-cli命令进入集群环境

使用redis-cli命令进入集群,注意: 输入redis-cli 命令时,附带的参数 -c 不能省略,详情看redis-cli的参考资料。

本地链接redis集群例子

cd /usr/local/redis

./bin/redis-cli -c -p 7001

 远程链接redis集群 例子

redis-cli.exe -c -h 192.168.253.140 -p 7001

2, 中止集群

cd /usr/local/redis

./bin/redis-cli redis-cli -p 7001 shutdown
./bin/redis-cli redis-cli -p 7002 shutdown
./bin/redis-cli redis-cli -p 7003 shutdown
./bin/redis-cli redis-cli -p 7004 shutdown
./bin/redis-cli redis-cli -p 7005 shutdown
./bin/redis-cli redis-cli -p 7006 shutdown

3,集群重启
有时候机器被重启了,须要从新启动集群,只须要将6台redis启起来,集群自动就会加载,恢复以前保存过的数据,不须要再次建立集群。

5、Jedis操做redis集群

1, example1

模拟的集群环境.在一台机器上启动多个redis..每一个redis对应的是不一样端口.在c192.168.253.140上启动的....总共3主3从 端口号对应的的是7001~7006。

import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

public class TestCluster {
    @Test
    public void test1() throws Exception {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        HostAndPort hostAndPort = new HostAndPort("192.168.253.140", 7000);
        HostAndPort hostAndPort1 = new HostAndPort("192.168.253.140", 7001);
        HostAndPort hostAndPort2 = new HostAndPort("192.168.253.140", 7002);
        HostAndPort hostAndPort3 = new HostAndPort("192.168.253.140", 7003);
        HostAndPort hostAndPort4 = new HostAndPort("192.168.253.140", 7004);
        HostAndPort hostAndPort5 = new HostAndPort("192.168.253.140", 7005);
        nodes.add(hostAndPort);
        nodes.add(hostAndPort1);
        nodes.add(hostAndPort2);
        nodes.add(hostAndPort3);
        nodes.add(hostAndPort4);
        nodes.add(hostAndPort5);
        JedisCluster jedisCluster = new JedisCluster(nodes, poolConfig);//JedisCluster中默认分装好了链接池.
        //redis内部会建立链接池,从链接池中获取链接使用,而后再把链接返回给链接池
        String string = jedisCluster.get("a");
        System.out.println(string);            
    }
}

 

6、使用redis-py-cluster模块操做redis集群

 使用python操做redis集群,须要安装redis-py-cluster模块。使用如下命令安装。

 pip install redis-py-cluster

 

2, 实例

from rediscluster import StrictRedisCluster
import sys

def redis_cluster():
    redis_nodes =  [{'host':'192.168.253.140','port':7001},
                    {'host':'192.168.253.140','port':7002},
                    {'host':'192.168.253.140','port':7003},
                    {'host':'192.168.253.140','port':7004},
                    {'host':'192.168.253.140','port':7005},
                    {'host':'192.168.253.140','port':7006}
                   ]
    try:
        redisconn = StrictRedisCluster(startup_nodes=redis_nodes)
    except Exception as msg :
        print(  msg )
        
    redisconn.set('name','admin')
    redisconn.set('age',18)
    print( "name is: ", redisconn.get('name') )
    print( "age  is: ", redisconn.get('age') )

    redisconn.flushdb()
   
redis_cluster()

 

 

 

总结:

  •     集群中各台机器的配置信息一致,Master/Slaver关系是在建立集群时由系统分配
  •     redis集群公用16384个slot,分配给不一样的Master
  •     每一个key最终都会位于某一个slot,读取key时会先转向到某一个slot,而后读取其中的值
  •     新增集群或减小集群(如新增或减小Master)会从新分配slot

 

补充资料:

1,Redis-cli使用时各参数的含义和使用方法

[root@localhost redis]# redis-cli --help
redis-cli 3.2.9

Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
  -h <hostname>      Server hostname (default: 127.0.0.1).
  -p <port>          Server port (default: 6379).
  -s <socket>        Server socket (overrides hostname and port).
  -a <password>      Password to use when connecting to the server.
  -r <repeat>        Execute specified command N times.
  -i <interval>      When -r is used, waits <interval> seconds per command.
                     It is possible to specify sub-second times like -i 0.1.
  -n <db>            Database number.
  -x                 Read last argument from STDIN.
  -d <delimiter>     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 <keys>  Simulate a cache workload with an 80-20 distribution.
  --slave            Simulate a slave showing commands received from the master.
  --rdb <filename>   Transfer an RDB dump from remote server to local file.
  --pipe             Transfer raw Redis protocol from stdin to server.
  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.
                     no reply is received within <n> 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 <pat>    Useful with --scan to specify a SCAN pattern.
  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.
                     The test will run for the specified amount of seconds.
  --eval <file>      Send an EVAL command using the Lua script at <file>.
  --ldb              Used with --eval enable the Redis Lua debugger.
  --ldb-sync-mode    Like --ldb but uses the synchronous Lua debugger, in
                     this mode the server is blocked and script changes are
                     are not rolled back from the server memory.
  --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
and settings.

[root@localhost redis]# 

2,往redis中缓存数据的时候,它怎么知道该缓存到哪一个服务器上呢??
  Redis 集群中内置了16384 个哈希槽,搭建集群时,每台服务器上已经分配了固定的哈希槽编号。当须要在 Redis 集群中放置一个key-value(数据) 时,redis 先对 key 使用 crc16 算法算出一个结果,而后把结果对 16384 求余数,这样每一个 key 都会对应一个编号在 0-16383 之间的哈希槽,redis 会根据求余的结果,把数据映射到不一样的redis服务器上。 

3,基本redis集群的操做命令:
redis 127.0.0.1:6379> info #查看server版本内存使用链接等信息
redis 127.0.0.1:6379> client list #获取客户链接列表
redis 127.0.0.1:6379> client kill 127.0.0.1:33441 #终止某个客户端链接
redis 127.0.0.1:6379> dbsize #当前保存key的数量
redis 127.0.0.1:6379> save #当即保存数据到硬盘
redis 127.0.0.1:6379> bgsave #异步保存数据到硬盘
redis 127.0.0.1:6379> flushdb #当前库中移除全部key
redis 127.0.0.1:6379> flushall #移除全部key从全部库中
redis 127.0.0.1:6379> lastsave #获取上次成功保存到硬盘的unix时间戳
redis 127.0.0.1:6379> monitor #实时监测服务器接收到的请求
redis 127.0.0.1:6379> slowlog len #查询慢查询日志条数
redis 127.0.0.1:6379> slowlog get #返回全部的慢查询日志,最大值取决于slowlog-max-len配置
redis 127.0.0.1:6379> slowlog get 2 #打印两条慢查询日志
redis 127.0.0.1:6379> slowlog reset #清空慢查询日志信息

更详细的命令请参考官网:http://redisdoc.com/
中文网站:http://www.redis.cn/commands.html

 

参考资料:
http://www.redis.cn/topics/cluster-tutorial.html
http://blog.csdn.net/myrainblues/article/details/25881535/
http://www.cnblogs.com/wuxl360/p/5920330.html
http://blog.csdn.net/yfkiss/article/details/38944179
http://diaocow.iteye.com/blog/1938032
http://www.cnblogs.com/guxiong/p/6270140.html
http://blog.csdn.net/ziele_008/article/details/51829429
centos配置ruby开发环境
https://my.oschina.net/u/1449160/blog/260764

http://www.cnblogs.com/gossip/p/5993401.html 

java

http://blog.csdn.net/junlong750/article/details/51362423

http://www.cnblogs.com/huali/p/5810054.html

使用强大的可视化工具redislive来监控咱们的redis

http://www.cnblogs.com/huangxincheng/archive/2016/06/08/5571185.html

理论知识:

http://www.cnblogs.com/wxd0108/p/5798498.html

redis集群密码设置

http://blog.csdn.net/jtbrian/article/details/53691540 

相关文章
相关标签/搜索