RedisTemplate zSet的使用, 根據點贊排序,和建立時間排序2種方式

使用Redis 對問題下的回答按點贊數排序的思路;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);
   }
相關文章
相關標籤/搜索