记录: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添加依赖
org.springframework.boot
spring-boot-starter-data-redis
2.配置RedisTemplate
2.1配置RedisTemplate
@Configuration
public class RedisConfig {
@Bean("redisTemplate")
public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
// 1.创建RedisTemplate对象
RedisTemplate redisTemplate = new RedisTemplate();
// 2.加载Redis配置
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
// 3.配置key序列化
RedisSerializer> stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// 4.配置Value序列化
Jackson2JsonRedisSerializer
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 {
@Nullable
Boolean add(K key, V value, double score);
@Nullable
Boolean addIfAbsent(K key, V value, double score);
@Nullable
Long add(K key, Set> tuples);
@Nullable
Long addIfAbsent(K key, Set> tuples);
@Nullable
Long remove(K key, Object... values);
@Nullable
Double incrementScore(K key, V value, double delta);
V randomMember(K key);
@Nullable
Set distinctRandomMembers(K key, long count);
@Nullable
List randomMembers(K key, long count);
ZSetOperations.TypedTuple randomMemberWithScore(K key);
@Nullable
Set> distinctRandomMembersWithScore(K key, long count);
@Nullable
List> randomMembersWithScore(K key, long count);
@Nullable
Long rank(K key, Object o);
@Nullable
Long reverseRank(K key, Object o);
@Nullable
Set range(K key, long start, long end);
@Nullable
Set> rangeWithScores(K key, long start, long end);
@Nullable
Set rangeByScore(K key, double min, double max);
@Nullable
Set> rangeByScoreWithScores(K key, double min, double max);
@Nullable
Set rangeByScore(K key, double min, double max, long offset, long count);
@Nullable
Set> rangeByScoreWithScores(K key, double min, double max, long offset, long count);
@Nullable
Set reverseRange(K key, long start, long end);
@Nullable
Set> reverseRangeWithScores(K key, long start, long end);
@Nullable
Set reverseRangeByScore(K key, double min, double max);
@Nullable
Set> reverseRangeByScoreWithScores(K key, double min, double max);
@Nullable
Set reverseRangeByScore(K key, double min, double max, long offset, long count);
@Nullable
Set> 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 popMin(K key);
@Nullable
Set> popMin(K key, long count);
@Nullable
ZSetOperations.TypedTuple popMin(K key, long timeout, TimeUnit unit);
@Nullable
default ZSetOperations.TypedTuple 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 popMax(K key);
@Nullable
Set> popMax(K key, long count);
@Nullable
ZSetOperations.TypedTuple popMax(K key, long timeout, TimeUnit unit);
@Nullable
default ZSetOperations.TypedTuple 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 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 difference(K key, K otherKey) {
return this.difference(key, (Collection)Collections.singleton(otherKey));
}
@Nullable
Set difference(K key, Collection otherKeys);
@Nullable
default Set> differenceWithScores(K key, K otherKey) {
return this.differenceWithScores(key, (Collection)Collections.singleton(otherKey));
}
@Nullable
Set> differenceWithScores(K key, Collection otherKeys);
@Nullable
Long differenceAndStore(K key, Collection otherKeys, K destKey);
@Nullable
default Set intersect(K key, K otherKey) {
return this.intersect(key, (Collection)Collections.singleton(otherKey));
}
@Nullable
Set intersect(K key, Collection otherKeys);
@Nullable
default Set> intersectWithScores(K key, K otherKey) {
return this.intersectWithScores(key, (Collection)Collections.singleton(otherKey));
}
@Nullable
Set> intersectWithScores(K key, Collection otherKeys);
@Nullable
default Set> intersectWithScores(K key, Collection otherKeys, Aggregate aggregate) {
return this.intersectWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
}
@Nullable
Set> intersectWithScores(K key, Collection otherKeys, Aggregate aggregate, Weights weights);
@Nullable
Long intersectAndStore(K key, K otherKey, K destKey);
@Nullable
Long intersectAndStore(K key, Collection otherKeys, K destKey);
@Nullable
default Long intersectAndStore(K key, Collection otherKeys, K destKey, Aggregate aggregate) {
return this.intersectAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
}
@Nullable
Long intersectAndStore(K key, Collection otherKeys, K destKey, Aggregate aggregate, Weights weights);
@Nullable
default Set union(K key, K otherKey) {
return this.union(key, (Collection)Collections.singleton(otherKey));
}
@Nullable
Set union(K key, Collection otherKeys);
@Nullable
default Set> unionWithScores(K key, K otherKey) {
return this.unionWithScores(key, (Collection)Collections.singleton(otherKey));
}
@Nullable
Set> unionWithScores(K key, Collection otherKeys);
@Nullable
default Set> unionWithScores(K key, Collection otherKeys, Aggregate aggregate) {
return this.unionWithScores(key, otherKeys, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
}
@Nullable
Set> unionWithScores(K key, Collection otherKeys, Aggregate aggregate, Weights weights);
@Nullable
Long unionAndStore(K key, K otherKey, K destKey);
@Nullable
Long unionAndStore(K key, Collection otherKeys, K destKey);
@Nullable
default Long unionAndStore(K key, Collection otherKeys, K destKey, Aggregate aggregate) {
return this.unionAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
}
@Nullable
Long unionAndStore(K key, Collection otherKeys, K destKey, Aggregate aggregate, Weights weights);
Cursor> scan(K key, ScanOptions options);
@Nullable
default Set rangeByLex(K key, Range range) {
return this.rangeByLex(key, range, Limit.unlimited());
}
@Nullable
Set rangeByLex(K key, Range range, Limit limit);
@Nullable
default Set reverseRangeByLex(K key, Range range) {
return this.reverseRangeByLex(key, range, Limit.unlimited());
}
@Nullable
Set reverseRangeByLex(K key, Range range, Limit limit);
RedisOperations getOperations();
public interface TypedTuple extends Comparable> {
@Nullable
V getValue();
@Nullable
Double getScore();
static ZSetOperations.TypedTuple of(V value, @Nullable Double score) {
return new DefaultTypedTuple(value, score);
}
}
}
以上,感谢。
2023年4月12日