Redis分布式搭建
一、Redis分布式缓存环境搭建
1.1 拷贝多一份redis,重新命名文件夹
1.2 修改redis2的配置文件redis.conf并启动验证
将端口号改成6380,启动的时候需要指明端口号或者是以配置文件启动,否则会以默认端口6379启动,则与redis1端口号产生冲突,启动redis2服务端
E:\Redis\redis-2.8.0-windows>redis-server.exe --port 6380
期间出现以下问题,大概意思是说内存不足 网上说重启电脑或者分配一下内存就好了
[11064] 17 Aug 11:35:43.960 #
The Windows version of Redis allocates a memory mapped heap for sharing with
the forked process used for persistence operations. In order to share this
memory, Windows allocates from the system paging file a portion equal to the
size of the Redis heap. At this time there is insufficient contiguous free
space available in the system paging file for this operation (Windows error
0x5AF). To work around this you may either increase the size of the system
paging file, or decrease the size of the Redis heap with the --maxheap flag.
Sometimes a reboot will defragment the system paging file sufficiently for
this operation to complete successfully.
可以将启动命令更换为
E:\Redis\redis-2.8.0-windows_2>redis-server.exe redis.windows.conf --maxheap 1gb --port 6380
启动redis2客户端:
E:\Redis\redis-2.8.0-windows_2>redis-cli.exe -p 6380
二、代码
2.1 properties文件修改
由于新增了redis2,需要在配置文件中添加其IP地址与端口号,后期增加的redis的信息都可以在这里增加
#redis config start
redis.max.total=20
redis.max.idle=10
redis.min.idle=2
redis.test.borrow=true
redis.test.return=false
redis1.ip=127.0.0.1
redis1.port=6379
redis2.ip=127.0.0.1
redis2.port=6380
#redis config end
2.2 创建RedisShardedPool
将之前的RedisPool.java的代码copy到RedisShardedPool中,由于redis部署方式分为单节点与集群部署,JedisPool连一台Redis,ShardedJedisPool连Redis的集群,通过一致性哈希算法决定把数据存到哪个redis上,所以将连接池修改为连接池改为ShardedJedisPool
private static ShardedJedisPool pool;
由于现在是弄Redis集群,需要将讲台redis的信息都写入,从properties文件中读取两台redis的IP地址与端口号
//redis1
private static String reids1Ip = PropertiesUtil.getProperty("redis1.ip");
private static Integer redis1Port = Integer.parseInt(PropertiesUtil.getProperty("redis1.port"));
//redis2
private static String reids2Ip = PropertiesUtil.getProperty("redis2.ip");
private static Integer redis2Port = Integer.parseInt(PropertiesUtil.getProperty("redis2.port"));
由于redis改用了sharedjdeispool,每个分片就是一个master,每个redis的信息不用,所以需要修改初始化代码
//IP、地址、超时时间
JedisShardInfo info1 = new JedisShardInfo(reids1Ip,redis1Port,1000*2);
//如果redis有密码,则可以调用info1.setPassword();
JedisShardInfo info2 = new JedisShardInfo(reids2Ip,redis2Port,1000*2);
List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo(2);
jedisShardInfoList.add(info1);
jedisShardInfoList.add(info2);
//配置、redis信息集合、分配策略、
//MURMUR_HASH代表redis分配的一致性算法
//通过keytags来确保key位于相同的shard
pool = new ShardedJedisPool(config,jedisShardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
2.3 RedisShardedPool完整代码