redis-zset排行榜 Java简单使用redis-zset实现排行榜
weixin_45121508 人气:3简单使用redis-zset实现排行榜
此方法实现一个根据某字段的查询次数进行排行,查询的次数越多排行越前(从大到小排序),适用于初学者
1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.注入RedisTemplate方法
@Autowired public RedisTemplate redisTemplate;
3.创建对象,用来接收redis数据
@Data public class RangeVo implements Serializable { private String shopName; private Double shopPrice; }
4.添加十条redis数据
@Test public void getzset4(){ String keyModel = "testList"; for (int i = 0; i < 10 ; i++) { int score = new Random().nextInt(50); String ss = "shop"+i; redisTemplate.opsForZSet().add(keyModel,ss,score); } }
5.根据某个key查询并每次查询score都会加1
@Test public void setOneValue(){ String keyModel = "testList"; String ss = "shop8"; Double aDouble = redisTemplate.opsForZSet().incrementScore(keyModel, ss, 1); System.out.println(aDouble); }
6.查询redis中所有数据,zset会根据score自动排序
@Test public void getList(){ String key = "testList"; List<RangeVo> list = new ArrayList<>(); /** 从小到大排序 返回value 和 score* 参数注释 key 为有序集合的key,1,50 是分数范围 1-50,0 是偏移量即从哪条数据开始排序, 5是取5条满足条件的数据*/ Set<ZSetOperations.TypedTuple<Object>> set = redisTemplate.opsForZSet().rangeByScoreWithScores(key,1,50,0,5); Iterator<ZSetOperations.TypedTuple<Object>> iterator = set.iterator(); while (iterator.hasNext()){ ZSetOperations.TypedTuple<Object> next = iterator.next(); RangeVo rangeVo = new RangeVo(); rangeVo.setShopName((String) next.getValue()); rangeVo.setShopPrice(next.getScore()); list.add(rangeVo); } System.out.println(list); }
加载全部内容