redis:redis cluster集群主从方案
Redis的安装以及cluster配置
下载redis最新的安装包
wget http://download.redis.io/releases/redis-3.0.7.tar.gz
解压
tar xzf redis-3.0.7.tar.gz
安装支持包tcl
yum install tcl 编译原文件
make
创建集群相关文件(方便管理)
mkdir cluster
cd cluster
mkdir 6379 6380 6381 6382 6383 6384
cluster下面每个目录中都创建一个redis.conf文件. 注意修改文件中的端口号:
port 6379 cluster-enabled yes cluster-config-file nodes_6379.conf cluster-node-timeout 5000 appendonly yes
把redis-server的可执行文件复制到cluster下面的各个目录, 然后打开6个shell终端,进入各个目录,启动每个实例, 命令如下:
./redis-server redis.conf
搭建集群
./redis-trib.rb create --replicas 1 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384
–replicas 1 表示我们希望为集群中的每个主节点创建一个从节点。
此时报错,发现缺少相应的ruby环境,如下安装相应环境:
yum install ruby
yum install rubygems
gem install redis
安装好环境后再次搭建集群
./redis-trib.rb create --replicas 1 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384
检测集群节点相关信息
./redis-trib.rb check 127.0.0.1:6379
进入某个节点验证
./redis-cli -c -h 127.0.0.1 -p 6379
package wusc.edu.demo.redis; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import redis.clients.jedis.JedisCluster; public class RedisClusterSpringTest { private static final Log log = LogFactory.getLog(RedisClusterSpringTest.class); public static void main(String[] args) { try { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml"); context.start(); JedisCluster jedisCluster = (JedisCluster) context.getBean("jedisCluster"); int num = 1000; String key = "yingjun"; String value = ""; for (int i=1; i <= num; i++){ // 存数据 //jedisCluster.set(key+i, "yingjun"+i); //jedisCluster.setex(key+i, 60, "yingjun"+i); // 取数据 value = jedisCluster.get(key+i); log.info(key+i + "=" + value); // 删除数据 //jedisCluster.del(key+i); //value = jedisCluster.get(key+i); //log.info(key+i + "=" + value); } context.stop(); } catch (Exception e) { log.error("==>RedisSpringTest context start error:", e); System.exit(0); } finally { log.info("===>System.exit"); System.exit(0); } } }