如何使用 Jedis 库建立与 Redis Sentinel 的连接?

问题描述 投票:0回答:3

如何使用 Jedis 库建立与 Redis Sentinel 服务器/集群的连接?

java redis jedis sentinel
3个回答
20
投票

Jedis 库是一个很棒的解决方案,但不幸的是文档很糟糕。

那么,

@Autowired private JedisSentinelPool pool;

public void mymethod() {
    Jedis jedis = null;
    try {
        jedis = pool.getResource();
        jedis.hset(....
    } catch (JedisException je) {
        throw je;
    } finally {
        if (jedis != null) pool.returnResource(jedis);
    }
}

当我使用 Spring 时,我需要:

<bean id="redisSentinel" class="redis.clients.jedis.JedisSentinelPool">
<constructor-arg index="0" value="mymaster" />
<constructor-arg index="1">
     <set>
         <value>hostofsentinel:26379</value>
    </set>
</constructor-arg>
<constructor-arg index="2" ref="jedisPoolConfig"/>
</bean>

8
投票

这是一个示例,当您不使用 Spring 并且需要通过 Jedis 与 Redis 哨兵管理的 Redis 主/从集进行简单连接时

public class JedisTestSentinelEndpoint {
    private static final String MASTER_NAME = "mymaster";
    public static final String PASSWORD = "foobared";
    private static final Set sentinels;
    static {
        sentinels = new HashSet();
        sentinels.add("mymaster-0.servers.example.com:26379");
        sentinels.add("mymaster-1.servers.example.com:26379");
        sentinels.add("mymaster-2.servers.example.com:26379");
    }

    public JedisTestSentinelEndpoint() {
    }

    private void runTest() throws InterruptedException {
        JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels);
        Jedis jedis = null;
            try {
                printer("Fetching connection from pool");
                jedis = pool.getResource();
                printer("Authenticating...");
                jedis.auth(PASSWORD);
                printer("auth complete...");
                Socket socket = jedis.getClient().getSocket();
                printer("Connected to " + socket.getRemoteSocketAddress());
                printer("Writing...");
                jedis.set("java-key-999", "java-value-999");
                printer("Reading...");
                jedis.get("java-key-999");
            } catch (JedisException e) {
                printer("Connection error of some sort!");
                printer(e.getMessage());
                Thread.sleep(2 * 1000);
            } finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
    }
...
}

来源:这篇博客文章有关连接到 Redis Sentinels。


1
投票

你尝试过Redisson吗?它提供哨兵自动主/从/哨兵发现和拓扑更新,您不需要处理连接、数据编码……这一切都是由 Redisson 完成的。这是代码示例:

Config config = new Config();
config.useSentinelServers()
   .setMasterName("mymaster")
   .addSentinelAddress("127.0.0.1:26389", "127.0.0.1:26379")

RedissonClient redisson = Redisson.create(config);

RMap<MyKey, MyValue> map = redisson.getMap("myMap");
map.put(new MyKey(), new MyValue());
© www.soinside.com 2019 - 2024. All rights reserved.