作者:HuPangpang_ | 来源:互联网 | 2023-08-24 10:49
开篇本篇用Redis实现文章的点赞,并由从点赞数有多到低排列。实现语言是JAVA,所以需要用的到包是jedis。本篇内容:介绍一下Redis.功能实现分析。功能实现。介绍一下Red
开篇
- 本篇用Redis实现文章的点赞,并由从点赞数有多到低排列。
- 实现语言是JAVA,所以需要用的到包是jedis。
- 本篇内容:
介绍一下Redis
Hash哈希:键值对存储 image.png
List列表:列表包含的元素,相同元素可以重复出现。 image.png
Set集合:无序排列,不能重复。 image.png
Sort Set 有序列表:列表特性,按值排序。 image.png
功能分析。
ps: article:92617 可以看成是一个对象的变量名。
功能实现
代码如下
//连接Redis
redis.clients.jedis.Jedis jedis = new redis.clients.jedis.Jedis("xxx.xx.x.xx");
System.out.println("success");
//创建4篇文章,用hash存储
jedis.hset("article:00001","title","文章1");
jedis.hset("article:00002","title","文章2");
jedis.hset("article:00003","title","文章3");
jedis.hset("article:00004","title","文章4");
Map stringStringMap = jedis.hgetAll("article:00004");
System.out.println(stringStringMap);
//创建一个有序集合,用来存文章的点赞排名。
jedis.zadd("score", 0, "article:00001");
jedis.zadd("score", 0, "article:00002");
jedis.zadd("score", 0, "article:00003");
jedis.zadd("score", 0, "article:00004");
System.out.println("文章获取到的"+jedis.zrange("score", 0, -1)
.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList()));
//现在模拟用户点赞。
//用户点赞就在该文章的基础上+1
jedis.zincrby("score",1,"article:00001");
jedis.zincrby("score",1,"article:00002");
jedis.zincrby("score",1,"article:00004");
jedis.zincrby("score",1,"article:00003");
jedis.zincrby("score",1,"article:00001");
jedis.zincrby("score",1,"article:00001");
jedis.zincrby("score",1,"article:00002");
jedis.zincrby("score",1,"article:00002");
jedis.zincrby("score",1,"article:00004");
jedis.zincrby("score",1,"article:00004");
jedis.zincrby("score",1,"article:00004");
jedis.zincrby("score",1,"article:00004");
//打印输出的list
Set score1 = jedis.zrevrangeWithScores("score", 0, -1);
for (Tuple t : score1) {
System.out.println(t.getElement()+":"+t.getScore());
}