java 连接redis哨兵_java连接redis-主从复制,哨兵模式

1 简单的主从复制模式

public class TextMS {

public static void main(String[] args) {

Jedis jedis_M = new Jedis("127.0.0.1",6379);

Jedis jedis_S = new Jedis("127.0.0.1",6380);

//从机连接到主机

jedis_S.slaveof("127.0.0.1",6379);

//主机写入

jedis_M.set("class","1122");

//从机读取

String result = jedis_S.get("class");

System.out.println(result);

}

2 哨兵模式

// 连接池配置

JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

jedisPoolConfig.setMaxTotal(10);

jedisPoolConfig.setMaxIdle(5);

jedisPoolConfig.setMinIdle(5);

// 哨兵信息

Setsentinels = new HashSet(Arrays.asList("192.168.11.128:6379", "192.168.11.129:6379", "192.168.11.130:6379"));

//创建连接池

//mymaster是我们配置给哨兵的服务名称

// 123 连接redis服务器的密码

JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, jedisPoolConfig, "123");

//获取客户端

Jedis jedis = pool.getResource();

//执行两个命令

jedis.set("mykey", "myvalue");

System.out.println(jedis.get("mykey"));

3 在spring中使用哨兵模式

测试

public static void testSpringSentinel() {

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:application.xml");

RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);

String retVal = (String) redisTemplate.execute((RedisOperations ops) -> {

ops.boundValueOps("mykey").set("myvalue");

String value = (String) ops.boundValueOps("mykey").get();

return value;

});

System.out.println(retVal);

}

你可能感兴趣的:(java,连接redis哨兵)