RedisTemplate zSet的使用, 根据点赞排序,和创建时间排序2种方式

使用Redis 对问题下的回答按点赞数排序的思路;
1根据问题id查出所有的回答列表;
2吧回答的ids添加到zset1中; key为id,value为赞的数量;(用于点赞排行);
//批量添加 Long add ( K var1 , Set < ZSetOperations . TypedTuple < V >> var2 ) ;
2-2吧回答的ids添加到zset2中;key为id,value为createTime.getLong();(用于创建时间排行);
3对回答进行点赞(取消)的时候
更改zset1中的指定key的value加减1;
4-1发表回答的时候zset1,zset2中增加元素,
 // redisTemplate . opsForZSet () . add ( key , 4565L , 13 ) ;
4-2删除的时候移除元素;
// redisTemplate . opsForZSet () . remove ( key , 4565L )
5获取排序后的分页数据;结果为回答的ids;
6迭代ids 去每个回答的id对应素材的缓存中取出对象;


    @Test
   public void test2(){
      String key = "mls_AnswerIdsByQuersionId:"+123;
      redisTemplate.opsForZSet().add(key,234L,5); //添加单条

      redisTemplate.opsForZSet().add(key,4565L,13);

      redisTemplate.opsForZSet().add(key,2345L,15);

      Set<ZSetOperations.TypedTuple<Long>> var2 = new HashSet<>();
      ZSetOperations.TypedTuple<Long> answerVoInZset1 = new AnswerVoInZset(2345L, 12);
      ZSetOperations.TypedTuple<Long> answerVoInZset2 = new AnswerVoInZset(5675L, 16);
      ZSetOperations.TypedTuple<Long> answerVoInZset4 = new AnswerVoInZset(4565L, 11);
      var2.add(answerVoInZset1);
      var2.add(answerVoInZset2);
      var2.add(answerVoInZset4);
      redisTempalte.opsForZSet().add(key, var2);//批量添加
      redisTemplate.opsForZSet().remove(key,4565L); //移除单个元素

      Set<Long> longs = redisTempalte.opsForZSet().reverseRange(key, 0, 3);
   }
//用于批量添加的对象;

   class AnswerVoInZset implements ZSetOperations.TypedTuple<Long>{
      Long id;
      double score;
      public AnswerVoInZset(Long id, double score) {
         this.id = id;
         this.score = score;
      }
      @Override
      public Long getValue() {
         return id;
      }
      @Override
      public Double getScore() {
         return score;
      }
      @Override
      public int compareTo(ZSetOperations.TypedTuple<Long> o) {
         AnswerVoInZset o1 = (AnswerVoInZset) o;
         return new Double(this.score).compareTo(o1.getScore());
      }
   }
   //时间排序;(参考别人的)
   @Resource(name = "redisTemplate")
   private RedisTemplate<String, Long> redisTempalte;

   public void addRecentBrowsingPosition(long userId, long positionId) {
      String key = "mls_AnswerIdsByQuersionId:" + 123;
      // 获取已缓存的最近浏览的职位
      ZSetOperations<String, Long> zSetOperations = redisTempalte.opsForZSet();
      // zset内部是按分数来排序的,这里用当前时间做分数
      zSetOperations.add(key, positionId, System.currentTimeMillis());
      // 环形结构--4,-3,-2,-1,0,1,2,3,4
      zSetOperations.removeRange(key, 0, -6);
   }

   public List<Long> getRecentBrowsingPositionIds(long userId) {
      if (userId <= 0) {
         return Collections.emptyList();
      }
      // 获取用户最近浏览的职位id
      String key = "mls_AnswerIdsByQuersionId:" + 123;
      Set<Long> positionIds = redisTempalte.opsForZSet().reverseRange(key, 0, 4);
      return new ArrayList<>(positionIds);
   }



你可能感兴趣的:(redis)