使用Redis 對問題下的回答按點贊數排序的思路;redis
@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); }