当前位置:   article > 正文

在Spring Boot微服务使用ZSetOperations操作Redis Zset(有序集合)

zsetoperations

记录:405

场景:在Spring Boot微服务使用RedisTemplate的ZSetOperations操作Redis Zset(有序集合)。

版本:JDK 1.8,Spring Boot 2.6.3,redis-6.2.5

1.微服务中Redis配置信息

1.1在application.yml中Redis配置信息

  1. spring:
  2. redis:
  3. host: 192.168.19.203
  4. port: 28001
  5. password: 12345678
  6. timeout: 50000

1.2加载简要逻辑

Spring Boot微服务在启动时,自动注解机制会读取application.yml的注入到RedisProperties对象。在Spring环境中就能取到Redis相关配置信息了。

类全称:org.springframework.boot.autoconfigure.data.redis.RedisProperties

1.3在pom.xml添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

2.配置RedisTemplate

2.1配置RedisTemplate

  1. @Configuration
  2. public class RedisConfig {
  3. @Bean("redisTemplate")
  4. public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
  5. // 1.创建RedisTemplate对象
  6. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
  7. // 2.加载Redis配置
  8. redisTemplate.setConnectionFactory(lettuceConnectionFactory);
  9. // 3.配置key序列化
  10. RedisSerializer<?> stringRedisSerializer = new StringRedisSerializer();
  11. redisTemplate.setKeySerializer(stringRedisSerializer);
  12. redisTemplate.setHashKeySerializer(stringRedisSerializer);
  13. // 4.配置Value序列化
  14. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
  15. ObjectMapper objMapper = new ObjectMapper();
  16. objMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  17. objMapper.activateDefaultTyping(objMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
  18. jackson2JsonRedisSerializer.setObjectMapper(objMapper);
  19. redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
  20. redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
  21. // 5.初始化RedisTemplate
  22. redisTemplate.afterPropertiesSet();
  23. return redisTemplate;
  24. }
  25. @Bean
  26. public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
  27. return redisTemplate.opsForZSet();
  28. }
  29. }

2.2解析

在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、ZSetOperations。

3.使用ZSetOperations操作Redis Zset(有序集合)

3.1简要说明

使用ZSetOperations操作Redis Zset(有序集合),常用操作:增、查、改、删、设置超时等。

3.2操作示例

  1. @RestController
  2. @RequestMapping("/hub/example/load")
  3. @Slf4j
  4. public class LoadController {
  5. @Autowired
  6. private RedisTemplate redisTemplate;
  7. @Autowired
  8. private ZSetOperations zSetOperations;
  9. /**
  10. * 操作ZSet,使用ZSetOperations,有序排列且无重复数据
  11. * 对应写命令: ZADD
  12. */
  13. @GetMapping("/zSetOperations")
  14. public Object loadData06() {
  15. log.info("ZSetOperations操作开始...");
  16. // 1.增
  17. zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);
  18. zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);
  19. zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);
  20. zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);
  21. zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);
  22. // 2.1查(通过下标查值,从0开始取第一个值)
  23. Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);
  24. set.forEach((value) -> {
  25. System.out.println("value=" + value);
  26. });
  27. // 2.2查(通过Score查值)
  28. set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);
  29. set.forEach((value) -> {
  30. System.out.println("value=" + value);
  31. });
  32. // 3.改
  33. zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);
  34. // 4.1取(取出Score最大的值,取出后队列中值会删除)
  35. ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");
  36. System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());
  37. // 4.2取(取出Score最小的值,取出后队列中值会删除)
  38. ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");
  39. System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());
  40. // 5.1删除指定值
  41. zSetOperations.remove("CityInfo:Hangzhou06", "上海");
  42. // 5.2按照Score分数大小删除
  43. zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);
  44. // 5.3删(删除全部)
  45. redisTemplate.delete("CityInfo:Hangzhou06");
  46. // 6.设置超时
  47. zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);
  48. zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);
  49. redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);
  50. redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);
  51. // 7.查询ZSet的元素个数
  52. Long size =zSetOperations.size("CityInfo:Hangzhou06");
  53. System.out.println("查询ZSet的元素个数,size="+size);
  54. log.info("ZSetOperations操作结束...");
  55. return "执行成功";
  56. }
  57. }

3.3测试验证

使用Postman测试。

请求RUL:http://127.0.0.1:18205/hub-205-redis/hub/example/load/zSetOperations

4.ZSetOperations接口

4.1接口

ZSetOperations是一个接口,默认实现类是DefaultZSetOperations。

接口:org.springframework.data.redis.core.ZSetOperations。

实现类:org.springframework.data.redis.core.DefaultZSetOperations。

4.2接口源码

在源码中,查看接口具体方法,可以快速了解该接口具备功能,以便在生产中能根据实际场景对号入座找到合适方法解决实际问题。

  1. public interface ZSetOperations<K, V> {
  2. @Nullable
  3. Boolean add(K key, V value, double score);
  4. @Nullable
  5. Boolean addIfAbsent(K key, V value, double score);
  6. @Nullable
  7. Long add(K key, Set<ZSetOperations.TypedTuple<V>> tuples);
  8. @Nullable
  9. Long addIfAbsent(K key, Set<ZSetOperations.TypedTuple<V>> tuples);
  10. @Nullable
  11. Long remove(K key, Object... values);
  12. @Nullable
  13. Double incrementScore(K key, V value, double delta);
  14. V randomMember(K key);
  15. @Nullable
  16. Set<V> distinctRandomMembers(K key, long count);
  17. @Nullable
  18. List<V> randomMembers(K key, long count);
  19. ZSetOperations.TypedTuple<V> randomMemberWithScore(K key);
  20. @Nullable
  21. Set<ZSetOperations.TypedTuple<V>> distinctRandomMembersWithScore(K key, long count);
  22. @Nullable
  23. List<ZSetOperations.TypedTuple<V>> randomMembersWithScore(K key, long count);
  24. @Nullable
  25. Long rank(K key, Object o);
  26. @Nullable
  27. Long reverseRank(K key, Object o);
  28. @Nullable
  29. Set<V> range(K key, long start, long end);
  30. @Nullable
  31. Set<ZSetOperations.TypedTuple<V>> rangeWithScores(K key, long start, long end);
  32. @Nullable
  33. Set<V> rangeByScore(K key, double min, double max);
  34. @Nullable
  35. Set<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max);
  36. @Nullable
  37. Set<V> rangeByScore(K key, double min, double max, long offset, long count);
  38. @Nullable
  39. Set<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max, long offset, long count);
  40. @Nullable
  41. Set<V> reverseRange(K key, long start, long end);
  42. @Nullable
  43. Set<ZSetOperations.TypedTuple<V>> reverseRangeWithScores(K key, long start, long end);
  44. @Nullable
  45. Set<V> reverseRangeByScore(K key, double min, double max);
  46. @Nullable
  47. Set<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max);
  48. @Nullable
  49. Set<V> reverseRangeByScore(K key, double min, double max, long offset, long count);
  50. @Nullable
  51. Set<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max, long offset, long count);
  52. @Nullable
  53. Long count(K key, double min, double max);
  54. @Nullable
  55. Long lexCount(K key, Range range);
  56. @Nullable
  57. ZSetOperations.TypedTuple<V> popMin(K key);
  58. @Nullable
  59. Set<ZSetOperations.TypedTuple<V>> popMin(K key, long count);
  60. @Nullable
  61. ZSetOperations.TypedTuple<V> popMin(K key, long timeout, TimeUnit unit);
  62. @Nullable
  63. default ZSetOperations.TypedTuple<V> popMin(K key, Duration timeout) {
  64. Assert.notNull(timeout, "Timeout must not be null");
  65. Assert.isTrue(!timeout.isNegative(), "Timeout must not be negative");
  66. return this.popMin(key, TimeoutUtils.toSeconds(timeout), TimeUnit.SECONDS);
  67. }
  68. @Nullable
  69. ZSetOperations.TypedTuple<V> popMax(K key);
  70. @Nullable
  71. Set<ZSetOperations.TypedTuple<V>> popMax(K key, long count);
  72. @Nullable
  73. ZSetOperations.TypedTuple<V> popMax(K key, long timeout, TimeUnit unit);
  74. @Nullable
  75. default ZSetOperations.TypedTuple<V> popMax(K key, Duration timeout) {
  76. Assert.notNull(timeout, "Timeout must not be null");
  77. Assert.isTrue(!timeout.isNegative(), "Timeout must not be negative");
  78. return this.popMin(key, TimeoutUtils.toSeconds(timeout), TimeUnit.SECONDS);
  79. }
  80. @Nullable
  81. Long size(K key);
  82. @Nullable
  83. Long zCard(K key);
  84. @Nullable
  85. Double score(K key, Object o);
  86. @Nullable
  87. List<Double> score(K key, Object... o);
  88. @Nullable
  89. Long removeRange(K key, long start, long end);
  90. @Nullable
  91. Long removeRangeByLex(K key, Range range);
  92. @Nullable
  93. Long removeRangeByScore(K key, double min, double max);
  94. @Nullable
  95. default Set<V> difference(K key, K otherKey) {
  96. return this.difference(key, (Collection)Collections.singleton(otherKey));
  97. }
  98. @Nullable
  99. Set<V> difference(K key, Collection<K> otherKeys);
  100. @Nullable
  101. default Set<ZSetOperations.TypedTuple<V>> differenceWithScores(K key, K otherKey) {
  102. return this.differenceWithScores(key, (Collection)Collections.singleton(otherKey));
  103. }
  104. @Nullable
  105. Set<ZSetOperations.TypedTuple<V>> differenceWithScores(K key, Collection<K> otherKeys);
  106. @Nullable
  107. Long differenceAndStore(K key, Collection<K> otherKeys, K destKey);
  108. @Nullable
  109. default Set<V> intersect(K key, K otherKey) {
  110. return this.intersect(key, (Collection)Collections.singleton(otherKey));
  111. }
  112. @Nullable
  113. Set<V> intersect(K key, Collection<K> otherKeys);
  114. @Nullable
  115. default Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, K otherKey) {
  116. return this.intersectWithScores(key, (Collection)Collections.singleton(otherKey));
  117. }
  118. @Nullable
  119. Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys);
  120. @Nullable
  121. default Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys, Aggregate aggregate) {
  122. return this.intersectWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
  123. }
  124. @Nullable
  125. Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys, Aggregate aggregate, Weights weights);
  126. @Nullable
  127. Long intersectAndStore(K key, K otherKey, K destKey);
  128. @Nullable
  129. Long intersectAndStore(K key, Collection<K> otherKeys, K destKey);
  130. @Nullable
  131. default Long intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {
  132. return this.intersectAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
  133. }
  134. @Nullable
  135. Long intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate, Weights weights);
  136. @Nullable
  137. default Set<V> union(K key, K otherKey) {
  138. return this.union(key, (Collection)Collections.singleton(otherKey));
  139. }
  140. @Nullable
  141. Set<V> union(K key, Collection<K> otherKeys);
  142. @Nullable
  143. default Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, K otherKey) {
  144. return this.unionWithScores(key, (Collection)Collections.singleton(otherKey));
  145. }
  146. @Nullable
  147. Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys);
  148. @Nullable
  149. default Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys, Aggregate aggregate) {
  150. return this.unionWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
  151. }
  152. @Nullable
  153. Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys, Aggregate aggregate, Weights weights);
  154. @Nullable
  155. Long unionAndStore(K key, K otherKey, K destKey);
  156. @Nullable
  157. Long unionAndStore(K key, Collection<K> otherKeys, K destKey);
  158. @Nullable
  159. default Long unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {
  160. return this.unionAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
  161. }
  162. @Nullable
  163. Long unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate, Weights weights);
  164. Cursor<ZSetOperations.TypedTuple<V>> scan(K key, ScanOptions options);
  165. @Nullable
  166. default Set<V> rangeByLex(K key, Range range) {
  167. return this.rangeByLex(key, range, Limit.unlimited());
  168. }
  169. @Nullable
  170. Set<V> rangeByLex(K key, Range range, Limit limit);
  171. @Nullable
  172. default Set<V> reverseRangeByLex(K key, Range range) {
  173. return this.reverseRangeByLex(key, range, Limit.unlimited());
  174. }
  175. @Nullable
  176. Set<V> reverseRangeByLex(K key, Range range, Limit limit);
  177. RedisOperations<K, V> getOperations();
  178. public interface TypedTuple<V> extends Comparable<ZSetOperations.TypedTuple<V>> {
  179. @Nullable
  180. V getValue();
  181. @Nullable
  182. Double getScore();
  183. static <V> ZSetOperations.TypedTuple<V> of(V value, @Nullable Double score) {
  184. return new DefaultTypedTuple(value, score);
  185. }
  186. }
  187. }

以上,感谢。

2023年4月12日

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/735619
推荐阅读
相关标签
  

闽ICP备14008679号