在如今并发的环境下,对大数据量的查询采用缓存是最好不过的了,本文使用redis搭建集群
(个人喜欢redis,对memcache不感冒)
redis是3.0后增加的集群功能,非常强大
集群中应该至少有三个节点,每个节点有一备份节点。这样算下来至少需要6台服务器
考虑到有些朋友的电脑配置不是很高,跑多个虚拟机就会卡,这边放出伪分布式和分布式
(2年前的配置)
前提先装好一个单例情况下的redis(这里就不多说了)
需要6个redis实例
搭建集群的步骤:
在/usr/local下 创建文件夹

这个我是把原来的单例redis改了个名字做的


进入redis01/bin
删除dump文件


修改端口

打开注释

复制多份
(真实环境下只需要一个就行,然后其余5台机子重复以上操作)

指定端口从7001到7006
这是真实环境下的

占用率

在redis源码文件夹下的src目录下。redis-trib.rb,这个ruby脚本

第四步:把redis-trib.rb文件复制到到redis-cluster目录下。
(真实环境下,只需要放在你某个节点机子上就行,他会自动遍历到其他的节点上的,我做的时候放在了01上)

执行ruby脚本之前,需要安装ruby环境,不然装不了
yum install ruby


yum install rubygems


安装redis-trib.rb运行依赖的ruby的包
这个gem可以网上下载,很多

(真实环境下只需要在其中一台机子上运行就行了)


进入各自的redis文件夹,分别启动所有的redis实例

启动成功

使用redis-trib.rb创建集群
不管是不是伪分布式,这只需要启动一次

成功~!
链接第一个节点

下面演示使用jedis来读写缓存
当然加入spring中一定要使用单例
@Test
public void testCluster() throws Exception {
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.1.193", 7001));
nodes.add(new HostAndPort("192.168.1.194", 7002));
nodes.add(new HostAndPort("192.168.1.195", 7003));
nodes.add(new HostAndPort("192.168.1.196", 7004));
nodes.add(new HostAndPort("192.168.1.197", 7005));
nodes.add(new HostAndPort("192.168.1.198", 7006));
JedisCluster jedisCluster = new JedisCluster(nodes);
jedisCluster.set("name", "lee");
jedisCluster.set("age", "18");
String name = jedisCluster.get("name");
String value = jedisCluster.get("age");
System.out.println(name);
System.out.println(value);
jedisCluster.close();
}
运行结果:
可以看到redis客户端上取数据的时候IP是不一样的