Redis集群搭建


Redis 集群通过分区(partition)来提供一定程度的可用性(availability): 即使集群中有一部分节点失效或者无法进行通讯, 集群也可以继续处理命令请求。

例子:模拟六台服务器三主三从,这个用6379,6380,6381,6389,6390,6391端口。

搭建集群的步骤(一个集群至少要有三个主节点。)

1.将rdb,aof文件都删除掉。
2.修改redis.conf文件

#是否开启集群
cluster-enabled yes
#结点名称  这里6379最好是port
cluster-config-file nodes-6379.conf
#节点离线超时时间
cluster-node-timeout 15000

3.将其服务都启动,会有节点node出现,确保所有的节点都出现后,配置其集群。
4.到redis的src目录中,执行该命令

#在这里,ip一定要真实ip,不能是localhost或者127.0.0.1
# --cluster-replicas 1:表示1个master下挂1个slave; --cluster-replicas 2:表示1个master下挂2个slave。
redis-cli --cluster create --cluster-replicas 1 192.168.242.110:6379 192.168.242.110:6380 192.168.242.110:6381 192.168.242.110:6389 192.168.242.110:6390 192.168.242.110:6391

启动集群

连接客户端redis/src下执行:

#-c : 开启集群模式; -h : 主机IP地址  -p : 端口号
/redis-cli -c -h 192.168.1.1 -p 8001

#查看集群信息
cluster info

#查看节点列表  从上面可以看出哪个slave挂在哪个master下
cluster nodes

关闭集群

关闭集群需要逐个关闭,使用命令:

/redis‐cli ‐c ‐h 192.168.1.1 ‐p 6379 shutdown
.......

注意:在创建集群的时候,需要把所有节点机器上的防火关闭,保证 Redis的服务端口和集群节点通信的 gossip 端口能通; systemctl stop firewalld # 临时关闭防火墙 。

java操作Redis集群(用spring Data redis)

配置:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring‐boot‐starter‐data‐redis</artifactId>
</dependency>
 
<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons‐pool2</artifactId>
</dependency>

server:
  port: 8080

spring:
  redis:
  database: 0
  timeout: 3000
  cluster:
    nodes: 192.168.0.61:8001,192.168.0.62:8002,192.168.0.63:8003,192.168.0.61:8004,192.168.0.62:8005,192.168.0.6
3:8006
  lettuce:
    pool:
      max‐idle: 50
      min‐idle: 10
      max‐active: 100
      max‐wait: 1000

测试:

@RestController
public class TestController {
 
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/test_cluster")
    public void testCluster() throws InterruptedException {
        stringRedisTemplate.opsForValue().set("user:name", "wangwu");
        System.out.println(stringRedisTemplate.opsForValue().get("user:name"));
    }
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值