使用测试代码如下:
public static void main(String[] args) {
String host = "172.*.*.*";
int port = 6379;
Jedis jedis = new Jedis(host, port);
jedis.ping();
//使用Jedis客户端操作有序集合Zset
jedis.zadd("programingLanguages", 1, "C");
jedis.zadd("programingLanguages", 2, "C++");
jedis.zadd("programingLanguages", 3, "Java");
jedis.zadd("programingLanguages", 0, "Python");
Set<String> programingLanguagesDesc = jedis.zrevrange("programingLanguages", 0, 3);
Set<String> programingLanguagesAsc = jedis.zrange("programingLanguages", 0, 3);
System.out.println("********降序********");
for (String language : programingLanguagesDesc) {
System.out.println(language);
}
System.out.println("********升序********");
for (String language : programingLanguagesAsc) {
System.out.println(language);
}
//对于字符串的下标,左数从0开始,右数从-1开始
System.out.println("****降序****取score占比最大的值********"+jedis.zrevrange("programingLanguages", 0, 0));
System.out.println("****升序****取score占比最大的值********"+jedis.zrange("programingLanguages", -1, -1));
System.out.println("****降序****取score占比前3名值********"+jedis.zrevrange("programingLanguages", 0, 2));
Boolean contains3=Optional.of(programingLanguagesAsc).map(score->score.contains("Java")).orElse(false);
System.out.println("***********是否包含score3***********"+contains3);
// Python,C,C++,Java 顺序
// 0 1 2 3
// -4 -3 -2 -1
//Java,C++,C,Python 降序
// 0 1 2 3
// -4 -3 -2 -1
}
运行反应值如下:
对于字符串的下标,左数从0开始,右数从-1开始
使用场景:
1:排行榜
2:检查本服务器是否为集群中最晚启动完成的服务器(分布式环境中可以使用时间戳为score,添加服务器ip地址)
/**
* 启动后, 在Redis中添加本服务器的启动时间
*/
@PostConstruct
public void register() {
try {
zSetOperations.add(ZSET_KEY_STARTED_SERVER_IPS, SERVER_IP, System.currentTimeMillis());
log.info("[{}] registered in Redis", SERVER_IP);
} catch (Exception e) {
log.warn("[{}] Redis Failed: {}, {}", SERVER_IP, ZSET_KEY_STARTED_SERVER_IPS, e.getMessage());
}
}
/**
* 退出前, 在Redis中删除本服务器的启动时间
*/
@PreDestroy
public void unregister() {
try {
zSetOperations.remove(ZSET_KEY_STARTED_SERVER_IPS, SERVER_IP);
log.info("[{}] removed from Redis", SERVER_IP);
} catch (Exception e) {
log.warn("[{}] Redis Failed: {}, {}", SERVER_IP, ZSET_KEY_STARTED_SERVER_IPS, e.getMessage());
}
}
public boolean isLatestStartedServer() {
try {
Set<String> serverIps = zSetOperations.range(ZSET_KEY_STARTED_SERVER_IPS, -1, -1);
if (CollectionUtils.isEmpty(serverIps)) {
register();
return true;
}
return Optional.of(serverIps)
.map(server -> server.contains(SERVER_IP))
.orElse(false);
} catch (Exception e) {
log.warn("Redis Failed: {}", e.getMessage());
return false;
}
}