java实现redis的哨兵模式的调用

1、安装redis 集群,1主1从 也可以是多主多从 redis 详细今后会在以后的文章中写出

配置redis-master 的配置文件 redis.conf

配置代码

  1. port 6379
  2. daemonize yes
  3. #protected-mode no
  4. dbfilename "1.db"
  5. bind 0.0.0.0

配置 redis-slave 的配置文件 redis.conf

配置代码

  1. port 6380
  2. daemonize yes
  3. dbfilename "2.db"
  4. bind 0.0.0.0
  5. #这里的IP必需通过程序可以访问到的IP地址
  6. slaveof 10.0.0.12 6379

配置哨兵配置文件 sentinel.conf

配置代码

  1. port 6388
  2. #protected-mode no
  3. bind 0.0.0.0
  4. daemonize yes
  5. logfile "/var/log/sentinel_6388.log"
  6. sentinel myid 818ae715a423ace06ab54a81bb4dac66de338377
  7. # 这里的IP,必需是通过程序可以访问的IP
  8. sentinel monitor master 10.0.0.12 6379 1
  9. sentinel down-after-milliseconds master 5000
  10. sentinel failover-timeout master 18000
  11. #如果有密码,这里就需要密码
  12. #sentinel auth-pass master 123456

启动redis

Shell代码

  1. bin/redis-server redis.conf 主和从

启动哨兵

Shell代码

  1. bin/redis-sentinel sentinel.conf

通过Java程序访问

Java代码

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. import redis.clients.jedis.Jedis;
  4. import redis.clients.jedis.JedisSentinelPool;
  5. public class RedisSentinelTest {
  6. public static void main(String[] args) {
  7. Set<String> sentinels = new HashSet<String>();
  8. String hostAndPort1 = "10.0.0.12:6388";
  9. sentinels.add(hostAndPort1);
  10. String clusterName = "master" ;
  11. JedisSentinelPool redisSentinelJedisPool = new JedisSentinelPool(clusterName,sentinels);
  12. Jedis jedis = null;
  13. try {
  14. jedis = redisSentinelJedisPool.getResource();
  15. //jedis.set("key", "aaa");
  16. System.out.println(jedis.get("key"));
  17. System.out.println(jedis.get("bbb"));
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. } finally {
  21. jedis.close();
  22. }
  23. redisSentinelJedisPool.close();
  24. }
  25. }
经验分享 程序员 微信小程序 职场和发展