ZSet 的一些案例
166字小于1分钟
2024-08-10
新闻浏览机制
/**
* @ClassName NewsDemo
* @Desciption 新闻浏览机制
* @Author MaRui
* @Date 2021/8/30 10:37
* @Version 1.0
*/
public class NewsDemo {
private static Jedis jedis = new Jedis("127.0.0.1", 6379);
public static void main(String[] args) {
NewsDemo demo = new NewsDemo();
for (int i = 0; i < 20; i++) {
demo.addNews(i + 1, i + 1);
}
long maxTimestamp = 18;
long minTimestamp = 2;
int pageNo = 1;
int pageSize = 10;
int startIndex = (pageNo - 1) * pageSize;
Set<Tuple> searchResult = demo.searchNews(maxTimestamp, minTimestamp, startIndex, pageSize);
System.out.println("搜索指定时间范围:" + searchResult);
}
/**
* 加入一篇新闻
* @param newsId
*/
public void addNews(long newsId, long timestamp) {
jedis.zadd("news", timestamp, String.valueOf(newsId));
}
/**
* 搜索新闻
* @param maxTimestamp
* @param minTimestamp
* @param index
* @param count
* @return
*/
public Set<Tuple> searchNews(long maxTimestamp, long minTimestamp, int index, int count) {
return jedis.zrevrangeByScoreWithScores("news", maxTimestamp, minTimestamp, index, count);
}
}