> 文章列表 > 在Spring Boot微服务使用ZSetOperations操作Redis Zset(有序集合)

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

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

记录: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.203port: 28001password: 12345678timeout: 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.初始化RedisTemplateredisTemplate.afterPropertiesSet();return redisTemplate;}@Beanpublic 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 {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate 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> {@NullableBoolean add(K key, V value, double score);@NullableBoolean addIfAbsent(K key, V value, double score);@NullableLong add(K key, Set<ZSetOperations.TypedTuple<V>> tuples);@NullableLong addIfAbsent(K key, Set<ZSetOperations.TypedTuple<V>> tuples);@NullableLong remove(K key, Object... values);@NullableDouble incrementScore(K key, V value, double delta);V randomMember(K key);@NullableSet<V> distinctRandomMembers(K key, long count);@NullableList<V> randomMembers(K key, long count);ZSetOperations.TypedTuple<V> randomMemberWithScore(K key);@NullableSet<ZSetOperations.TypedTuple<V>> distinctRandomMembersWithScore(K key, long count);@NullableList<ZSetOperations.TypedTuple<V>> randomMembersWithScore(K key, long count);@NullableLong rank(K key, Object o);@NullableLong reverseRank(K key, Object o);@NullableSet<V> range(K key, long start, long end);@NullableSet<ZSetOperations.TypedTuple<V>> rangeWithScores(K key, long start, long end);@NullableSet<V> rangeByScore(K key, double min, double max);@NullableSet<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max);@NullableSet<V> rangeByScore(K key, double min, double max, long offset, long count);@NullableSet<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K key, double min, double max, long offset, long count);@NullableSet<V> reverseRange(K key, long start, long end);@NullableSet<ZSetOperations.TypedTuple<V>> reverseRangeWithScores(K key, long start, long end);@NullableSet<V> reverseRangeByScore(K key, double min, double max);@NullableSet<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max);@NullableSet<V> reverseRangeByScore(K key, double min, double max, long offset, long count);@NullableSet<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K key, double min, double max, long offset, long count);@NullableLong count(K key, double min, double max);@NullableLong lexCount(K key, Range range);@NullableZSetOperations.TypedTuple<V> popMin(K key);@NullableSet<ZSetOperations.TypedTuple<V>> popMin(K key, long count);@NullableZSetOperations.TypedTuple<V> popMin(K key, long timeout, TimeUnit unit);@Nullabledefault 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);}@NullableZSetOperations.TypedTuple<V> popMax(K key);@NullableSet<ZSetOperations.TypedTuple<V>> popMax(K key, long count);@NullableZSetOperations.TypedTuple<V> popMax(K key, long timeout, TimeUnit unit);@Nullabledefault 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);}@NullableLong size(K key);@NullableLong zCard(K key);@NullableDouble score(K key, Object o);@NullableList<Double> score(K key, Object... o);@NullableLong removeRange(K key, long start, long end);@NullableLong removeRangeByLex(K key, Range range);@NullableLong removeRangeByScore(K key, double min, double max);@Nullabledefault Set<V> difference(K key, K otherKey) {return this.difference(key, (Collection)Collections.singleton(otherKey));}@NullableSet<V> difference(K key, Collection<K> otherKeys);@Nullabledefault Set<ZSetOperations.TypedTuple<V>> differenceWithScores(K key, K otherKey) {return this.differenceWithScores(key, (Collection)Collections.singleton(otherKey));}@NullableSet<ZSetOperations.TypedTuple<V>> differenceWithScores(K key, Collection<K> otherKeys);@NullableLong differenceAndStore(K key, Collection<K> otherKeys, K destKey);@Nullabledefault Set<V> intersect(K key, K otherKey) {return this.intersect(key, (Collection)Collections.singleton(otherKey));}@NullableSet<V> intersect(K key, Collection<K> otherKeys);@Nullabledefault Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, K otherKey) {return this.intersectWithScores(key, (Collection)Collections.singleton(otherKey));}@NullableSet<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys);@Nullabledefault Set<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys, Aggregate aggregate) {return this.intersectWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));}@NullableSet<ZSetOperations.TypedTuple<V>> intersectWithScores(K key, Collection<K> otherKeys, Aggregate aggregate, Weights weights);@NullableLong intersectAndStore(K key, K otherKey, K destKey);@NullableLong intersectAndStore(K key, Collection<K> otherKeys, K destKey);@Nullabledefault Long intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {return this.intersectAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));}@NullableLong intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate, Weights weights);@Nullabledefault Set<V> union(K key, K otherKey) {return this.union(key, (Collection)Collections.singleton(otherKey));}@NullableSet<V> union(K key, Collection<K> otherKeys);@Nullabledefault Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, K otherKey) {return this.unionWithScores(key, (Collection)Collections.singleton(otherKey));}@NullableSet<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys);@Nullabledefault Set<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys, Aggregate aggregate) {return this.unionWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));}@NullableSet<ZSetOperations.TypedTuple<V>> unionWithScores(K key, Collection<K> otherKeys, Aggregate aggregate, Weights weights);@NullableLong unionAndStore(K key, K otherKey, K destKey);@NullableLong unionAndStore(K key, Collection<K> otherKeys, K destKey);@Nullabledefault Long unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {return this.unionAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));}@NullableLong unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate, Weights weights);Cursor<ZSetOperations.TypedTuple<V>> scan(K key, ScanOptions options);@Nullabledefault Set<V> rangeByLex(K key, Range range) {return this.rangeByLex(key, range, Limit.unlimited());}@NullableSet<V> rangeByLex(K key, Range range, Limit limit);@Nullabledefault Set<V> reverseRangeByLex(K key, Range range) {return this.reverseRangeByLex(key, range, Limit.unlimited());}@NullableSet<V> reverseRangeByLex(K key, Range range, Limit limit);RedisOperations<K, V> getOperations();public interface TypedTuple<V> extends Comparable<ZSetOperations.TypedTuple<V>> {@NullableV getValue();@NullableDouble getScore();static <V> ZSetOperations.TypedTuple<V> of(V value, @Nullable Double score) {return new DefaultTypedTuple(value, score);}}
}

以上,感谢。

2023年4月12日