Redis主从复制(一个Master/多个slave)配合哨兵模式(观察者)
@SpringBootTest
public class MasterSlaveTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void testMasterReadWrite(){//配置文件端口为6379
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set("role", "master6379");
Object role = valueOperations.get("role");
System.out.println(role);
}
@Test
void testSlaveRead(){//配置文件端口为6380
ValueOperations valueOperations = redisTemplate.opsForValue();
Object role = valueOperations.get("role");
System.out.println(role);
}
}
Redis集群模式下代码案例1
配置application文件
spring:
redis:
cluster: #redis 集群配置
nodes: 192.168.126.129:8010,192.168.126.129:8011,192.168.126.129:8012,192.168.126.129:8013,192.168.126.129:8014,192.168.126.129:8015
max-redirects: 3 #最大跳转次数
timeout: 5000 #超时时间
database: 0
jedis: #连接池
pool:
max-idle: 8
max-wait: 0
代码案例
package com.cy.redis;
@SpringBootTest
public class RedisClusterTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void testMasterReadWrite(){
//1.获取数据操作对象
ValueOperations valueOperations = redisTemplate.opsForValue();
//2.读写数据
valueOperations.set("city","beijing");
Object city=valueOperations.get("city");
System.out.println(city);
}
}
Redis集群模式下代码案例2
@Test
void testJedisCluster()throws Exception{
//创建多个节点
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.126.129",8010));
nodes.add(new HostAndPort("192.168.126.129",8011));
nodes.add(new HostAndPort("192.168.126.129",8012));
nodes.add(new HostAndPort("192.168.126.129",8013));
nodes.add(new HostAndPort("192.168.126.129",8014));
nodes.add(new HostAndPort("192.168.126.129",8015));
JedisCluster jedisCluster = new JedisCluster(nodes);
//使用jedisCluster操作redis
jedisCluster.set("test", "cluster");
String str = jedisCluster.get("test");
System.out.println(str);
//关闭连接池
jedisCluster.close();
}