简单实现Redis缓存中的排序功能

edis 是 Redis 官方首选的 Java 客户端开发包。这篇文章我们将介绍如何使用 Sorted Set 排序集合(zsets)。

Sorted Set 跟一个集合一样,它是不会存在重复的数值,最大的不同是 Sorted Set 中每个元素都是经过排序的。

我们先看一些命令:


import java.util.HashMap;
import java.util.Map;
import redis.clients.jedis.Jedis;

public class TestJedis {

public static void main(String[] args) {

    String key = "mostUsedLanguages";

    Jedis jedis = new Jedis("localhost");

     //Adding a value with score to the set
     jedis.zadd(key,100,"Java");//ZADD
     //We could add more than one value in one calling
     Map<Double, String> scoreMembers = new HashMap<Double, String>();
     scoreMembers.put(90d, "Python");
     scoreMembers.put(80d, "Javascript");
     jedis.zadd(key, scoreMembers);
     //We could get the score for a member
     System.out.println("Number of Java users:" + jedis.zscore(key, "Java"));
     //We could get the number of elements on the set
     System.out.println("Number of elements:" + jedis.zcard(key));//ZCARD

     }

}

上述例子中我们看到了 Zset 命令,为了将元素添加到 zet 中,我们使用 zadd 方法,不同的是我们还传递了一个元素的评分值,我们可以使用 Map 对象来一次传递很多个对象,而 zadd 方法可用于增加和更新已有元素的评分值。

我们可使用 zscore 来获取某元素的评分,通过 zcard 获取元素个数。

下面的例子我们可看到来自 zsets 的其他命令:

01
import java.util.Set;
02

03
import redis.clients.jedis.Jedis;
04
import redis.clients.jedis.Tuple;
05
public class TestJedis {
06

07
public static void main(String[] args) {
08
String key = “mostUsedLanguages”;
09
Jedis jedis = new Jedis(“localhost”);
10

11
//get all the elements sorted from bottom to top
12
System.out.println(jedis.zrange(key, 0, -1));
13

14
//get all the elements sorted from top to bottom
15
System.out.println(jedis.zrevrange(key, 0, -1));
16
//We could get the elements with the associated score
17
Set elements = jedis.zrevrangeWithScores(key, 0, -1);
18
for(Tuple tuple: elements){
19
System.out.println(tuple.getElement() + “-” + tuple.getScore());
20
}
21

22
//We can increment a score for a element using ZINCRBY
23
System.out.println(“Score before zincrby:” + jedis.zscore(key, “Python”));
24
//Incrementing the element score
25
jedis.zincrby(key, 1, “Python”);
26
System.out.println(“Score after zincrby:” + jedis.zscore(key, “Python”));
27
}
28
}
通过 zrange 我们能获取给定范围的元素,它将返回经过排序后的元素列表(自底向上),也可以通过 zrevrrange 获取自顶向下的元素列表。Redis 还允许我们通过关联的评分来获取元素,传递 “withscores“ 参数即可。使用 Jedis API 的 zrevrangeWithScores 方法可返回对象集合。另外一个有用的命令是 zincrby 可用于增加元素的评分值。

zsets 还有其他的命令,这里我们只是介绍跟 Jedis API 相关的一些基本用法。这里还有一些关于排序集合的介绍。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值