首页  

redis使用zset保留最近的数据     所属分类 redis 浏览量 1440
使用 时间戳 或 时间戳负值 作为 score,保留最近的N条记录

使用jedis


<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.0.1</version>
</dependency>



  Remove all elements in the sorted set at key with rank between start and end. 
  Start and end are 0-based with rank 0 being the element with the lowest score. 
  Both start and end can be negative numbers, 
  where they indicate offsets starting at the element with the highest rank.
   
  For example: 
  -1 is the element with the highest score, 
  -2 the element with the second highest score and so forth.
   
  Time complexity: O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of elements removed by the operation
   
  public Long zremrangeByRank(final String key, final long start, final long stop) 
  
  public Long zadd(final String key, final double score, final String member)
  
  
  public Set zrevrangeWithScores(final String key, final long start, final long stop)
  


// 时间戳负值作为 score String key = "zsetkey"; Date time = new Date(); int size = 5; double score = 0 - time.getTime(); jedis.zadd(key, score, time+""); Long zcard = jedis.zcard(key); System.out.println("zcard="+zcard); Long zcount = jedis.zcount(key, Long.MIN_VALUE, Long.MAX_VALUE); System.out.println("zcount="+zcount); Set<Tuple> zsets = jedis.zrangeByScoreWithScores(key, Long.MIN_VALUE, Long.MAX_VALUE,0,size); System.out.println(zsets); int start = size; int stop = Integer.MAX_VALUE; jedis.zremrangeByRank(key, start, stop); System.out.println("*******"); // 时间戳 作为 score key = "zsetkey2"; score = time.getTime(); jedis.zadd(key, score, time+""); zcard = jedis.zcard(key); System.out.println("zcard="+zcard); zcount = jedis.zcount(key, 0, Long.MAX_VALUE); System.out.println("zcount="+zcount); zsets = jedis.zrangeByScoreWithScores(key, 0, Long.MAX_VALUE,0,size); System.out.println(zsets); start = 0 - size - 9; // size = Integer.MIN_VALUE stop = 0 - size; jedis.zremrangeByRank(key, start, stop); 注意两种情况的 zremrangeByRank 方法 start 和 stop 参数区别 完整代码 https://gitee.com/dyyx/redisdemo/blob/master/src/main/java/dyyx/ZsetTest.java

上一篇     下一篇
git reset 版本回退

redis集群方案

Mysql innodb 为何建议使用自增列作为主键

B+树 与 B树 索引

B树与红黑树,为什么数据库使用B树索引

联合索引与最左匹配原则