我正在寻找使用redis sentinel的jedis示例。我无法使用jedis设施作为哨兵,我找不到任何好的例子或文件。
答案 0 :(得分:19)
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>
答案 1 :(得分:3)
这是一个例子,当你不使用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();
}
}
}
...
}
来源:This blog post关于连接到Redis Sentinels。
答案 2 :(得分:1)
你试过Redisson吗?它提供了哨兵自动主/从/哨兵发现和拓扑更新,你不需要处理连接,数据编码......所有这些都是由Redisson完成的。这是代码示例:
def create_directory(path)
system 'mkdir', '-p', path
end