|
| 1 | +package com.loopers.application.product; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import org.springframework.data.redis.core.RedisCallback; |
| 5 | +import org.springframework.data.redis.core.StringRedisTemplate; |
| 6 | +import org.springframework.data.redis.serializer.RedisSerializer; |
| 7 | +import org.springframework.stereotype.Component; |
| 8 | + |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +@Component |
| 12 | +@RequiredArgsConstructor |
| 13 | +public class RankingRedisReader { |
| 14 | + private final StringRedisTemplate redisTemplate; |
| 15 | + |
| 16 | + public RankingInfo getDailyRanking(String date, Long productId) { |
| 17 | + String key = "ranking:all:" + date; |
| 18 | + String member = String.valueOf(productId); |
| 19 | + |
| 20 | + RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); |
| 21 | + byte[] keyBytes = serializer.serialize(key); |
| 22 | + byte[] memberBytes = serializer.serialize(member); |
| 23 | + |
| 24 | + @SuppressWarnings("unchecked") |
| 25 | + List<Object> results = (List<Object>) redisTemplate.executePipelined((RedisCallback<Object>) connection -> { |
| 26 | + connection.zScore(keyBytes, memberBytes); // -> Double (or null) |
| 27 | + connection.zRevRank(keyBytes, memberBytes); // -> Long (or null) 0-base |
| 28 | + connection.zCard(keyBytes); // -> Long |
| 29 | + return null; |
| 30 | + }); |
| 31 | + |
| 32 | + Double score = (Double) results.get(0); |
| 33 | + Long revRank0 = (Long) results.get(1); |
| 34 | + Long total = (Long) results.get(2); |
| 35 | + |
| 36 | + Integer rank = (revRank0 == null) ? null : Math.toIntExact(revRank0 + 1); |
| 37 | + |
| 38 | + return new RankingInfo(date, score, rank, total); |
| 39 | + } |
| 40 | +} |
0 commit comments