Redis 集群,官方方案需要6个节点,3个主3个从。
- 安装依赖软件
安装:ruby
yum -y install ruby
安装:rubygems-2.7.4.tgz
https://rubygems.org/rubygems/rubygems-2.7.4.tgz
tar -xzvf rubygems-2.7.4.tgz
cd rubygems-2.7.4
ruby setup.rb
安装:redis-4.0.1.gem
https://rubygems.org/downloads/redis-4.0.1.gem
gem install -l ./redis-4.0.1.gem
- 安装redis
安装:redis
http://download.redis.io/releases/redis-4.0.6.tar.gz
tar -xzvf redis-4.0.6.tar.gz
cd redis-4.0.6
make
- 集群配置
cd redis-4.0.6
mkdir -p clus/6401 clus/6402 clus/6403 clus/6404 clus/6405 clus/6406
cp redis.conf clus/6401 其它目录个一份配置文件
vi clus/6401/redis.conf
daemonize yes
port 6401
bind 127.0.0.1
cluster-enabled yes
cluster-config-file /opt/redis-4.0.6/clus/6401/nodes-6401.conf
cluster-node-timeout 5000
slave-serve-stale-data yes
dir /opt/redis-4.0.6/clus/6401/
dbfilename dump.rdb
appendonly yes
appendfilename "appendonly.aof"
其它几个端口的配置文件,参照以上替换6401为6402...6406的端口即可
- 创建集群
启动节点:节点需要加入进去,必须先启动
/opt/redis-4.0.6/src/redis-server /opt/redis-4.0.6/clus/6401/redis.conf
/opt/redis-4.0.6/src/redis-server /opt/redis-4.0.6/clus/6402/redis.conf
/opt/redis-4.0.6/src/redis-server /opt/redis-4.0.6/clus/6403/redis.conf
/opt/redis-4.0.6/src/redis-server /opt/redis-4.0.6/clus/6404/redis.conf
/opt/redis-4.0.6/src/redis-server /opt/redis-4.0.6/clus/6405/redis.conf
/opt/redis-4.0.6/src/redis-server /opt/redis-4.0.6/clus/6406/redis.conf
创建集群:集群只需创建一次,以后只需启动节点即可。正常情况,执行以下命令后,会提示集群创建的结果,其中包含三个master和三个slave节点。
/opt/redis-4.0.6/src/redis-trib.rb create --replicas 1 127.0.0.1:6401 127.0.0.1:6402 127.0.0.1:6403 127.0.0.1:6404 127.0.0.1:6405 127.0.0.1:6406
- 集群测试
连接其中一台redis,要带 -c 参数,进行设置值,再连接另外任意节点进行查看,测试成功,连接命令:
/opt/redis-4.0.6/src/redis-cli -c -p 6401
- JAVA连接集群
maven配置依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
客户端代码:
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(100000);
config.setMaxIdle(5);
config.setMaxWaitMillis(1000 * 100);
config.setTestOnBorrow(true);
// 定义集群信息
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo("127.0.0.1", 6401));
shards.add(new JedisShardInfo("127.0.0.1", 6402));
shards.add(new JedisShardInfo("127.0.0.1", 6403));
shards.add(new JedisShardInfo("127.0.0.1", 6404));
shards.add(new JedisShardInfo("127.0.0.1", 6405));
shards.add(new JedisShardInfo("127.0.0.1", 6406));
// 定义集群连接接池
ShardedJedisPool shardedJedisPool = new ShardedJedisPool(config,shards);
// 连接池中获取连接
ShardedJedis redis = pool.getResource();
redis.set("name", "finish");
String val = redis.get("name");
redis.close();
System.out.println(val);