功能:
-
getMasterNames 从Sentinel集群从获取master名称列表
依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
源码:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisConnectionException;
/**
* @author Dotions 2016年4月7日 下午4:12:11
*/
public class RedisSentinelUtils {
private static final Logger LOG = LoggerFactory.getLogger(RedisSentinelUtils.class);
/**
* 从 Sentinel 集群中获取 Master 名称列表
* Set value format is ip:port
*/
public static Set<String> getMasterNames(Set<String> sentinels) {
if (sentinels == null || sentinels.isEmpty()) {
return Collections.emptySet();
}
Set<String> masterNames = new LinkedHashSet<String>();
Iterator<String> it = sentinels.iterator();
Jedis sentinel = null;
String shap = null;
while (it.hasNext()) {
shap = it.next();
try {
final HostAndPort hap = toHostAndPort(Arrays.asList(shap.split(":")));
sentinel = new Jedis(hap.getHost(), hap.getPort());
String sInfo = sentinel.info();
if (StringUtils.isNotBlank(sInfo)) {
InputStream is = new ByteArrayInputStream(sInfo.getBytes());
Properties p = new Properties();
p.load(is);
// check master number
int masterN = Integer.parseInt(p.getProperty("sentinel_masters"));
if (masterN > 0) {
String val = null;
String status = null;
String masterName = null;
for (int i = 0; i < masterN; i++) {
val = p.getProperty("master" + i);
String[] kv = val.split(",");
status = kv[1].split("=")[1];
masterName = kv[0].split("=")[1];
// Master status=ok
if ("ok".equals(status)) {
masterNames.add(masterName);
}
LOG.info("masterName={}, status={}", masterName, status);
}
} else {
LOG.info("Not found any master in sentinel {}", shap);
}
} else {
LOG.error("Sentinel command execute fail, result is blank.");
}
} catch (JedisConnectionException ce) {
sentinels.remove(shap);
LOG.error(String.format("[%s] connection exception, cause by: ", shap), ce);
} catch (Exception e) {
LOG.error(String.format("[%s] runtime exception, cause by: ", shap), e);
} finally {
sentinel.close();
}
}
return masterNames;
}
private static HostAndPort toHostAndPort(List<String> hostAndPort) {
return new HostAndPort(hostAndPort.get(0), Integer.parseInt(hostAndPort.get(1)));
}
}