在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.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日

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微服务架构是一种新兴的软件架构体系,它将一个大型应用程序分解为多个独立的服务,每个服务都提供一定的功能,服务之间通过轻量级的通信机制协同工作,构成一个松散耦合的系统。 而 Spring Boot 是一个快速创建基于 Spring 的应用程序的框架。它采用约定大于配置的方式,简化了 Spring 应用程序的开发,同时提高了应用程序的可维护性。 Redis 是一种高速缓存数据库,具有高并发和低延迟的特点。它能够在存储和读取大规模数据时提供快速的性能和可靠的持久性。 秒杀是指在限定时间内,将大量的请求按照系统预设的规则进行处理,从而实现购买或者抢购等活动。在传统的单机架构中,秒杀的高并发场景经常会导致系统崩溃或者响应缓慢,因此需要采用新的技术来解决这个问题。 将微服务Spring BootRedis 结合起来,可以有效地解决秒杀系统的高并发问题。采用微服务架构,可以将每个服务拆分为独立的功能,提高系统的可扩展性和可维护性。使用 Spring Boot 框架,则可以快速搭建服务,并利用它的依赖注入和 AOP 等特性,增加代码的复用性和可维护性。而 Redis 则可以作为高速缓存数据库,提高系统的响应速度和可靠性。 在秒杀场景中,可以将商品和库存信息缓存在 Redis 中,同时采用消息队列来控制请求的流量,避免系统瞬时崩溃。在秒杀活动开始前,将商品信息和库存信息加载到 Redis 中,由 Redis 进行管理,并在秒杀结束后将结果写入数据库中。通过这种方式,可以提高系统的吞吐量和可靠性,同时保证秒杀活动的公平性和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值