赞
踩
记录: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配置信息
- spring:
- redis:
- host: 192.168.19.203
- port: 28001
- password: 12345678
- timeout: 50000
1.2加载简要逻辑
Spring Boot微服务在启动时,自动注解机制会读取application.yml的注入到RedisProperties对象。在Spring环境中就能取到Redis相关配置信息了。
类全称:org.springframework.boot.autoconfigure.data.redis.RedisProperties
1.3在pom.xml添加依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
2.配置RedisTemplate
2.1配置RedisTemplate
- @Configuration
- public class RedisConfig {
- @Bean("redisTemplate")
- public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
- // 1.创建RedisTemplate对象
- RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
- // 2.加载Redis配置
- redisTemplate.setConnectionFactory(lettuceConnectionFactory);
- // 3.配置key序列化
- RedisSerializer<?> stringRedisSerializer = new StringRedisSerializer();
- redisTemplate.setKeySerializer(stringRedisSerializer);
- redisTemplate.setHashKeySerializer(stringRedisSerializer);
- // 4.配置Value序列化
- Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
- ObjectMapper objMapper = new ObjectMapper();
- objMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
- objMapper.activateDefaultTyping(objMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
- jackson2JsonRedisSerializer.setObjectMapper(objMapper);
- redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
- redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
- // 5.初始化RedisTemplate
- redisTemplate.afterPropertiesSet();
- return redisTemplate;
- }
- @Bean
- public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
- return redisTemplate.opsForZSet();
- }
- }
2.2解析
在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、ZSetOperations。
3.使用ZSetOperations操作Redis Zset(有序集合)
3.1简要说明
使用ZSetOperations操作Redis Zset(有序集合),常用操作:增、查、改、删、设置超时等。
3.2操作示例
- @RestController
- @RequestMapping("/hub/example/load")
- @Slf4j
- public class LoadController {
- @Autowired
- private RedisTemplate redisTemplate;
- @Autowired
- private ZSetOperations zSetOperations;
- /**
- * 操作ZSet,使用ZSetOperations,有序排列且无重复数据
- * 对应写命令: ZADD
- */
- @GetMapping("/zSetOperations")
- public Object loadData06() {
- log.info("ZSetOperations操作开始...");
- // 1.增
- zSetOperations.add("CityInfo:Hangzhou06", "杭州", 20);
- zSetOperations.add("CityInfo:Hangzhou06", "苏州", 10);
- zSetOperations.add("CityInfo:Hangzhou06", "上海", 30);
- zSetOperations.add("CityInfo:Hangzhou06", "北京", 101);
- zSetOperations.add("CityInfo:Hangzhou06", "宁波", 999);
- // 2.1查(通过下标查值,从0开始取第一个值)
- Set set = zSetOperations.range("CityInfo:Hangzhou06", 1, 4);
- set.forEach((value) -> {
- System.out.println("value=" + value);
- });
- // 2.2查(通过Score查值)
- set = zSetOperations.rangeByScore("CityInfo:Hangzhou06", 29, 60);
- set.forEach((value) -> {
- System.out.println("value=" + value);
- });
- // 3.改
- zSetOperations.add("CityInfo:Hangzhou06", "杭州", 99);
- // 4.1取(取出Score最大的值,取出后队列中值会删除)
- ZSetOperations.TypedTuple obj1 = zSetOperations.popMax("CityInfo:Hangzhou06");
- System.out.println("取出最大值,value=" + obj1.getValue() + ",Score=" + obj1.getScore());
- // 4.2取(取出Score最小的值,取出后队列中值会删除)
- ZSetOperations.TypedTuple obj2 = zSetOperations.popMin("CityInfo:Hangzhou06");
- System.out.println("取出最小值,value=" + obj2.getValue() + ",Score=" + obj2.getScore());
- // 5.1删除指定值
- zSetOperations.remove("CityInfo:Hangzhou06", "上海");
- // 5.2按照Score分数大小删除
- zSetOperations.removeRangeByScore("CityInfo:Hangzhou06", 1, 100);
- // 5.3删(删除全部)
- redisTemplate.delete("CityInfo:Hangzhou06");
- // 6.设置超时
- zSetOperations.add("CityInfo:Hangzhou06", "杭州", 21);
- zSetOperations.add("CityInfo:Hangzhou06", "苏州", 11);
- redisTemplate.boundValueOps("CityInfo:Hangzhou06").expire(5, TimeUnit.MINUTES);
- redisTemplate.expire("CityInfo:Hangzhou06", 10, TimeUnit.MINUTES);
- // 7.查询ZSet的元素个数
- Long size =zSetOperations.size("CityInfo:Hangzhou06");
- System.out.println("查询ZSet的元素个数,size="+size);
- log.info("ZSetOperations操作结束...");
- return "执行成功";
- }
- }
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接口源码
在源码中,查看接口具体方法,可以快速了解该接口具备功能,以便在生产中能根据实际场景对号入座找到合适方法解决实际问题。
- public interface ZSetOperations<K, V> {
- @Nullable
- Boolean add(K key, V value, double score);
- @Nullable
- Boolean addIfAbsent(K key, V value, double score);
- @Nullable
- Long add(K key, Set<ZSetOperations.TypedTuple<V>> tuples);
- @Nullable
- Long addIfAbsent(K key, Set<ZSetOperations.TypedTuple<V>> tuples);
- @Nullable
- Long remove(K key, Object... values);
- @Nullable
- Double incrementScore(K key, V value, double delta);
- V randomMember(K key);
- @Nullable
- Set<V> distinctRandomMembers(K key, long count);
- @Nullable
- List<V> randomMembers(K key, long count);
- ZSetOperations.TypedTuple<V> randomMemberWithScore(K key);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> distinctRandomMembersWithScore(K key, long count);
- @Nullable
- List<ZSetOperations.TypedTuple<V>> randomMembersWithScore(K key, long count);
- @Nullable
- Long rank(K key, Object o);
- @Nullable
- Long reverseRank(K key, Object o);
- @Nullable
- Set<V> range(K key, long start, long end);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> rangeWithScores(K key, long start, long end);
- @Nullable
- Set<V> rangeByScore(K key, double min, double max);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max);
- @Nullable
- Set<V> rangeByScore(K key, double min, double max, long offset, long count);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max, long offset, long count);
- @Nullable
- Set<V> reverseRange(K key, long start, long end);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> reverseRangeWithScores(K key, long start, long end);
- @Nullable
- Set<V> reverseRangeByScore(K key, double min, double max);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max);
- @Nullable
- Set<V> reverseRangeByScore(K key, double min, double max, long offset, long count);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max, long offset, long count);
- @Nullable
- Long count(K key, double min, double max);
- @Nullable
- Long lexCount(K key, Range range);
- @Nullable
- ZSetOperations.TypedTuple<V> popMin(K key);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> popMin(K key, long count);
- @Nullable
- ZSetOperations.TypedTuple<V> popMin(K key, long timeout, TimeUnit unit);
- @Nullable
- default ZSetOperations.TypedTuple<V> popMin(K key, Duration timeout) {
- Assert.notNull(timeout, "Timeout must not be null");
- Assert.isTrue(!timeout.isNegative(), "Timeout must not be negative");
- return this.popMin(key, TimeoutUtils.toSeconds(timeout), TimeUnit.SECONDS);
- }
- @Nullable
- ZSetOperations.TypedTuple<V> popMax(K key);
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> popMax(K key, long count);
- @Nullable
- ZSetOperations.TypedTuple<V> popMax(K key, long timeout, TimeUnit unit);
- @Nullable
- default ZSetOperations.TypedTuple<V> popMax(K key, Duration timeout) {
- Assert.notNull(timeout, "Timeout must not be null");
- Assert.isTrue(!timeout.isNegative(), "Timeout must not be negative");
- return this.popMin(key, TimeoutUtils.toSeconds(timeout), TimeUnit.SECONDS);
- }
- @Nullable
- Long size(K key);
- @Nullable
- Long zCard(K key);
- @Nullable
- Double score(K key, Object o);
- @Nullable
- List<Double> score(K key, Object... o);
- @Nullable
- Long removeRange(K key, long start, long end);
- @Nullable
- Long removeRangeByLex(K key, Range range);
- @Nullable
- Long removeRangeByScore(K key, double min, double max);
- @Nullable
- default Set<V> difference(K key, K otherKey) {
- return this.difference(key, (Collection)Collections.singleton(otherKey));
- }
- @Nullable
- Set<V> difference(K key, Collection<K> otherKeys);
- @Nullable
- default Set<ZSetOperations.TypedTuple<V>> differenceWithScores(K key, K otherKey) {
- return this.differenceWithScores(key, (Collection)Collections.singleton(otherKey));
- }
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> differenceWithScores(K key, Collection<K> otherKeys);
- @Nullable
- Long differenceAndStore(K key, Collection<K> otherKeys, K destKey);
- @Nullable
- default Set<V> intersect(K key, K otherKey) {
- return this.intersect(key, (Collection)Collections.singleton(otherKey));
- }
- @Nullable
- Set<V> intersect(K key, Collection<K> otherKeys);
- @Nullable
- default Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, K otherKey) {
- return this.intersectWithScores(key, (Collection)Collections.singleton(otherKey));
- }
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys);
- @Nullable
- default Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys, Aggregate aggregate) {
- return this.intersectWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
- }
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys, Aggregate aggregate, Weights weights);
- @Nullable
- Long intersectAndStore(K key, K otherKey, K destKey);
- @Nullable
- Long intersectAndStore(K key, Collection<K> otherKeys, K destKey);
- @Nullable
- default Long intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {
- return this.intersectAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
- }
- @Nullable
- Long intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate, Weights weights);
- @Nullable
- default Set<V> union(K key, K otherKey) {
- return this.union(key, (Collection)Collections.singleton(otherKey));
- }
- @Nullable
- Set<V> union(K key, Collection<K> otherKeys);
-
- @Nullable
- default Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, K otherKey) {
- return this.unionWithScores(key, (Collection)Collections.singleton(otherKey));
- }
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys);
- @Nullable
- default Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys, Aggregate aggregate) {
- return this.unionWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
- }
- @Nullable
- Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys, Aggregate aggregate, Weights weights);
- @Nullable
- Long unionAndStore(K key, K otherKey, K destKey);
- @Nullable
- Long unionAndStore(K key, Collection<K> otherKeys, K destKey);
- @Nullable
- default Long unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {
- return this.unionAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
- }
- @Nullable
- Long unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate, Weights weights);
- Cursor<ZSetOperations.TypedTuple<V>> scan(K key, ScanOptions options);
- @Nullable
- default Set<V> rangeByLex(K key, Range range) {
- return this.rangeByLex(key, range, Limit.unlimited());
- }
- @Nullable
- Set<V> rangeByLex(K key, Range range, Limit limit);
- @Nullable
- default Set<V> reverseRangeByLex(K key, Range range) {
- return this.reverseRangeByLex(key, range, Limit.unlimited());
- }
- @Nullable
- Set<V> reverseRangeByLex(K key, Range range, Limit limit);
- RedisOperations<K, V> getOperations();
- public interface TypedTuple<V> extends Comparable<ZSetOperations.TypedTuple<V>> {
- @Nullable
- V getValue();
-
- @Nullable
- Double getScore();
-
- static <V> ZSetOperations.TypedTuple<V> of(V value, @Nullable Double score) {
- return new DefaultTypedTuple(value, score);
- }
- }
- }
以上,感谢。
2023年4月12日
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。