封装Redis模块(最全面的教程!)

打印 上一主题 下一主题

主题 1073|帖子 1073|积分 3219

1.环境搭建

1.创建模块


2.查看是否交给父模块管理


3.引入依靠

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.     <modelVersion>4.0.0</modelVersion>
  6.     <parent>
  7.         <groupId>com.sunxiansheng</groupId>
  8.         <artifactId>sunrays-common</artifactId>
  9.         <version>1.0</version>
  10.     </parent>
  11.     <version>1.0</version>
  12.     <artifactId>common-redis-starter</artifactId>
  13.     <dependencies>
  14.         <!-- redis -->
  15.         <dependency>
  16.             <groupId>org.springframework.boot</groupId>
  17.             <artifactId>spring-boot-starter-data-redis</artifactId>
  18.             <!-- 排除,防止日志冲突 -->
  19.             <exclusions>
  20.                 <exclusion>
  21.                     <artifactId>spring-boot-starter-logging</artifactId>
  22.                     <groupId>org.springframework.boot</groupId>
  23.                 </exclusion>
  24.             </exclusions>
  25.         </dependency>
  26.         <!-- 集成 redis 所需 commons-pool2 -->
  27.         <dependency>
  28.             <groupId>org.apache.commons</groupId>
  29.             <artifactId>commons-pool2</artifactId>
  30.         </dependency>
  31.     </dependencies>
  32. </project>
复制代码
4.自动配置

1.目次


2.RedisAutoConfiguration.java

  1. package com.sunxiansheng.redis.config;
  2. import org.springframework.context.annotation.Configuration;
  3. /**
  4. * Description: Redis自动配置类
  5. *
  6. * @Author sun
  7. * @Create 2024/11/15 20:41
  8. * @Version 1.0
  9. */
  10. @Configuration
  11. public class RedisAutoConfiguration {
  12. }
复制代码
3.spring.factories

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  2. com.sunxiansheng.redis.config.RedisAutoConfiguration
复制代码
2.重写RedisTemplate

1.引入Jackson

  1.         <!-- 重写RedisTemplate所需要的Jackson -->
  2.         <dependency>
  3.             <groupId>com.fasterxml.jackson.core</groupId>
  4.             <artifactId>jackson-databind</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>com.fasterxml.jackson.core</groupId>
  8.             <artifactId>jackson-annotations</artifactId>
  9.         </dependency>
复制代码
2.编写RedisConfig.java


  1. package com.sunxiansheng.redis.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.JsonInclude;
  4. import com.fasterxml.jackson.annotation.PropertyAccessor;
  5. import com.fasterxml.jackson.databind.DeserializationFeature;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.data.redis.connection.RedisConnectionFactory;
  11. import org.springframework.data.redis.core.RedisTemplate;
  12. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  13. import org.springframework.data.redis.serializer.RedisSerializer;
  14. import org.springframework.data.redis.serializer.StringRedisSerializer;
  15. /**
  16. * Redis配置类,会将 Object 类型序列化为 JSON 格式,然后将其作为字符串存储在 Redis 中。
  17. * 当从 Redis 中读取时,会将 JSON 字符串反序列化回具体的 Object 类型数据,直接强制转换即可,无需手动解析 JSON。
  18. */
  19. @Configuration
  20. public class RedisConfig {
  21.     /**
  22.      * 自定义RedisTemplate Bean,配置Key和Value的序列化方式。
  23.      * Key采用String序列化,Value采用JSON序列化,支持对象直接转为JSON格式存储在Redis中。
  24.      *
  25.      * @param redisConnectionFactory Redis连接工厂,用于创建RedisTemplate连接
  26.      * @return 配置完成的RedisTemplate实例,用于Redis数据操作
  27.      */
  28.     @Bean
  29.     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  30.         RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  31.         redisTemplate.setConnectionFactory(redisConnectionFactory);
  32.         // 设置Key的序列化方式为StringRedisSerializer,以便Key以字符串格式存储,便于人类读取
  33.         RedisSerializer<String> stringSerializer = new StringRedisSerializer();
  34.         redisTemplate.setKeySerializer(stringSerializer);          // 序列化Redis键
  35.         redisTemplate.setHashKeySerializer(stringSerializer);      // 序列化Hash结构的键
  36.         // 设置Value和HashValue的序列化方式为Jackson2JsonRedisSerializer,以便Value以JSON格式存储
  37.         Jackson2JsonRedisSerializer<Object> jacksonSerializer = jackson2JsonRedisSerializer();
  38.         redisTemplate.setValueSerializer(jacksonSerializer);       // 序列化Redis值
  39.         redisTemplate.setHashValueSerializer(jacksonSerializer);   // 序列化Hash结构的值
  40.         // 初始化设置的配置
  41.         redisTemplate.afterPropertiesSet();
  42.         return redisTemplate;
  43.     }
  44.     /**
  45.      * 配置Jackson序列化器,以支持复杂Java对象的序列化和反序列化。
  46.      * 使用Jackson2JsonRedisSerializer将对象序列化为JSON字符串,从而提高Redis中的可读性和兼容性。
  47.      *
  48.      * @return 配置好的Jackson2JsonRedisSerializer实例,指定序列化格式为JSON
  49.      */
  50.     private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
  51.         // 创建Jackson2JsonRedisSerializer,指定泛型为Object,支持序列化任意Java对象
  52.         Jackson2JsonRedisSerializer<Object> jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
  53.         // 创建ObjectMapper用于配置JSON序列化方式
  54.         ObjectMapper objectMapper = new ObjectMapper();
  55.         // 设置可见性,允许访问所有字段(包括私有和保护字段),确保所有属性都被序列化和反序列化
  56.         objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  57.         // 配置反序列化时忽略未知属性,防止因JSON中多余字段导致反序列化错误
  58.         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  59.         // 序列化时忽略空值属性,节省存储空间
  60.         objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  61.         // 启用类型信息,确保反序列化时能够恢复原始对象类型
  62.         objectMapper.activateDefaultTyping(
  63.                 BasicPolymorphicTypeValidator.builder()
  64.                         .allowIfSubType(Object.class)
  65.                         .build(),
  66.                 ObjectMapper.DefaultTyping.NON_FINAL
  67.         );
  68.         // 将配置好的ObjectMapper设置到Jackson2JsonRedisSerializer中,应用上述配置
  69.         jacksonSerializer.setObjectMapper(objectMapper);
  70.         return jacksonSerializer;
  71.     }
  72. }
复制代码
3.RedisAutoConfiguration.java 导入配置类


3.Redis工具类

1.RBase.java Redis基础工具类

  1. package com.sunxiansheng.redis.utils;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import java.util.Collection;
  4. import java.util.concurrent.TimeUnit;
  5. /**
  6. * Redis基础工具类,提供一些基础的操作
  7. *
  8. * @Author sun
  9. * @Create 2024/11/14 14:25
  10. * @Version 1.0
  11. */
  12. public class RBase {
  13.     protected RedisTemplate<String, Object> redisTemplate;
  14.     public RBase(RedisTemplate<String, Object> redisTemplate) {
  15.         this.redisTemplate = redisTemplate;
  16.     }
  17.     /**
  18.      * 默认的key分隔符
  19.      */
  20.     private static final String DEFAULT_KEY_SEPARATOR = ":";
  21.     /**
  22.      * 构建缓存key(使用默认的key分隔符)
  23.      *
  24.      * @param parts 多个字符串拼接成缓存key
  25.      * @return 拼接后的缓存key
  26.      */
  27.     public String buildKeyByDefaultSeparator(String... parts) {
  28.         return String.join(DEFAULT_KEY_SEPARATOR, parts);
  29.     }
  30.     /**
  31.      * 构建缓存key(使用自定义的key分隔符)
  32.      *
  33.      * @param separator 自定义的key分隔符
  34.      * @param parts     多个字符串拼接成缓存key
  35.      * @return 拼接后的缓存key
  36.      */
  37.     public String buildKeyByCustomSeparator(String separator, String... parts) {
  38.         return String.join(separator, parts);
  39.     }
  40.     /**
  41.      * 删除单个key
  42.      *
  43.      * @param key 键
  44.      * @return 如果键不存在,返回false;如果删除成功,返回true
  45.      */
  46.     public Boolean delete(String key) {
  47.         if (key == null || key.isEmpty()) {
  48.             throw new IllegalArgumentException("Key cannot be null or empty");
  49.         }
  50.         return redisTemplate.delete(key);
  51.     }
  52.     /**
  53.      * 批量删除key
  54.      *
  55.      * @param keys 键的集合
  56.      * @return 成功删除的键的数量,键不存在不计数
  57.      */
  58.     public Long deleteBatch(Collection<String> keys) {
  59.         if (keys == null || keys.isEmpty()) {
  60.             return 0L;
  61.         }
  62.         return redisTemplate.delete(keys);
  63.     }
  64.     /**
  65.      * 指定缓存失效时间
  66.      *
  67.      * @param key     键
  68.      * @param timeout 失效时间(小于等于0 表示 永久有效)
  69.      * @param unit    时间单位
  70.      * @return 设置成功返回true,失败返回false
  71.      */
  72.     public Boolean expire(String key, long timeout, TimeUnit unit) {
  73.         if (key == null || key.isEmpty()) {
  74.             throw new IllegalArgumentException("Key cannot be null or empty");
  75.         }
  76.         if (timeout <= 0) {
  77.             // 或直接返回 true,表示设置为永久有效
  78.             return false;
  79.         }
  80.         return redisTemplate.expire(key, timeout, unit);
  81.     }
  82.     /**
  83.      * 指定缓存失效时间(时间单位:秒)
  84.      *
  85.      * @param key     键
  86.      * @param timeout 失效时间(单位:秒,小于等于0 表示 永久有效)
  87.      * @return 设置成功返回true,失败返回false
  88.      */
  89.     public Boolean expire(String key, long timeout) {
  90.         return expire(key, timeout, TimeUnit.SECONDS);
  91.     }
  92.     /**
  93.      * 获取缓存失效时间
  94.      *
  95.      * @param key 键
  96.      * @return 缓存失效时间(秒)。键不存在返回-2,键存在但没有设置过期时间返回-1
  97.      */
  98.     public Long getExpire(String key) {
  99.         if (key == null || key.isEmpty()) {
  100.             throw new IllegalArgumentException("Key cannot be null or empty");
  101.         }
  102.         return redisTemplate.getExpire(key);
  103.     }
  104.     /**
  105.      * 判断key是否存在
  106.      *
  107.      * @param key 键
  108.      * @return 存在返回true,不存在返回false
  109.      */
  110.     public Boolean hasKey(String key) {
  111.         if (key == null || key.isEmpty()) {
  112.             throw new IllegalArgumentException("Key cannot be null or empty");
  113.         }
  114.         return redisTemplate.hasKey(key);
  115.     }
  116.     /**
  117.      * 转换缓存中的对象为指定类型
  118.      *
  119.      * @param value 缓存中的对象
  120.      * @param type  要转换的目标类型
  121.      * @param <T>   返回的泛型类型
  122.      * @return 转换后的对象
  123.      * @throws ClassCastException 如果对象不能转换为指定类型
  124.      */
  125.     protected <T> T convertValue(Object value, Class<T> type) {
  126.         if (value == null) {
  127.             return null;
  128.         }
  129.         // Long类型的特殊处理,因为Redis中的数据会自动反序列化为Integer
  130.         if (type == Long.class && value instanceof Integer) {
  131.             return type.cast(((Integer) value).longValue());
  132.         }
  133.         if (type.isInstance(value)) {
  134.             return type.cast(value);
  135.         } else {
  136.             throw new ClassCastException("Redis中的对象运行类型与请求转换的类型不匹配,请优先检查Redis配置类是否保存了对象原始信息!期待类型:"
  137.                     + type.getName() + ",实际类型:"
  138.                     + value.getClass().getName());
  139.         }
  140.     }
  141. }
复制代码
2.RString.java

  1. package com.sunxiansheng.redis.utils;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import java.util.concurrent.TimeUnit;
  4. /**
  5. * Description: Redis的String类型操作
  6. *
  7. * @Author sun
  8. * @Create 2024/11/14 14:50
  9. * @Version 1.1
  10. */
  11. public class RString extends RBase {
  12.     /**
  13.      * 构造器给父类注入RedisTemplate
  14.      *
  15.      * @param redisTemplate RedisTemplate实例
  16.      */
  17.     public RString(RedisTemplate<String, Object> redisTemplate) {
  18.         super(redisTemplate);
  19.     }
  20.     /**
  21.      * 设置缓存值
  22.      *
  23.      * @param key   键
  24.      * @param value 值
  25.      */
  26.     public void set(String key, Object value) {
  27.         validateKeyAndValue(key, value);
  28.         redisTemplate.opsForValue().set(key, value);
  29.     }
  30.     /**
  31.      * 设置缓存值并设置过期时间
  32.      *
  33.      * @param key     键
  34.      * @param value   值
  35.      * @param timeout 过期时间
  36.      * @param unit    时间单位
  37.      */
  38.     public void setWithExpire(String key, Object value, final long timeout, final TimeUnit unit) {
  39.         validateKeyAndValue(key, value);
  40.         validateTimeoutAndUnit(timeout, unit);
  41.         redisTemplate.opsForValue().set(key, value, timeout, unit);
  42.     }
  43.     /**
  44.      * 设置缓存值并设置过期时间(单位:秒)
  45.      *
  46.      * @param key     键
  47.      * @param value   值
  48.      * @param timeout 过期时间
  49.      */
  50.     public void setWithExpire(String key, Object value, final long timeout) {
  51.         setWithExpire(key, value, timeout, TimeUnit.SECONDS);
  52.     }
  53.     /**
  54.      * 设置缓存值,如果key不存在,则设置成功,并指定过期时间
  55.      *
  56.      * @param key     键
  57.      * @param value   值
  58.      * @param timeout 过期时间
  59.      * @param unit    时间单位
  60.      * @return 是否设置成功
  61.      */
  62.     public Boolean setIfAbsent(String key, Object value, long timeout, TimeUnit unit) {
  63.         validateKeyAndValue(key, value);
  64.         validateTimeoutAndUnit(timeout, unit);
  65.         return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit);
  66.     }
  67.     /**
  68.      * 设置缓存值,如果key不存在,则设置成功,并指定过期时间(单位:秒)
  69.      *
  70.      * @param key     键
  71.      * @param value   值
  72.      * @param timeout 过期时间
  73.      * @return 是否设置成功
  74.      */
  75.     public Boolean setIfAbsent(String key, Object value, long timeout) {
  76.         return setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
  77.     }
  78.     /**
  79.      * 获取缓存值并进行类型转换
  80.      *
  81.      * @param key  键
  82.      * @param type 返回值的类型
  83.      * @return 转换后的对象,若类型不匹配则抛出异常
  84.      */
  85.     public <T> T get(String key, Class<T> type) {
  86.         Object value = redisTemplate.opsForValue().get(key);
  87.         return convertValue(value, type);
  88.     }
  89.     /**
  90.      * 获取缓存值并设置新值
  91.      *
  92.      * @param key   键
  93.      * @param value 新值
  94.      * @param type  返回值的类型
  95.      * @param <T>   返回值的类型
  96.      * @return 旧值,类型为 T
  97.      */
  98.     public <T> T getAndSet(String key, T value, Class<T> type) {
  99.         Object oldValue = redisTemplate.opsForValue().getAndSet(key, value);
  100.         return convertValue(oldValue, type);
  101.     }
  102.     /**
  103.      * 根据 delta 值调整缓存中的数值
  104.      *
  105.      * @param key   键
  106.      * @param delta 调整步长,正数表示增加,负数表示减少
  107.      * @return 调整后的值
  108.      */
  109.     public Long changeByDelta(String key, long delta) {
  110.         if (key == null) {
  111.             throw new IllegalArgumentException("Key 不能为空!");
  112.         }
  113.         return redisTemplate.opsForValue().increment(key, delta);
  114.     }
  115.     /**
  116.      * 验证键和值的合法性
  117.      */
  118.     private void validateKeyAndValue(String key, Object value) {
  119.         if (key == null || value == null) {
  120.             throw new IllegalArgumentException("Key 和 Value 不能为空!");
  121.         }
  122.     }
  123.     /**
  124.      * 验证超时时间和单位的合法性
  125.      */
  126.     private void validateTimeoutAndUnit(long timeout, TimeUnit unit) {
  127.         if (timeout <= 0 || unit == null) {
  128.             throw new IllegalArgumentException("超时时间必须大于 0,时间单位不能为空!");
  129.         }
  130.     }
  131. }
复制代码
3.RList.java

  1. package com.sunxiansheng.redis.utils;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import java.util.ArrayList;
  4. import java.util.Collection;
  5. import java.util.List;
  6. /**
  7. * Description: Redis的List类型操作
  8. *
  9. * @Author sun
  10. * @Create 2024/11/14 14:50
  11. * @Version 1.0
  12. */
  13. public class RList extends RBase {
  14.     /**
  15.      * 构造器给父类注入RedisTemplate
  16.      *
  17.      * @param redisTemplate RedisTemplate实例
  18.      */
  19.     public RList(RedisTemplate<String, Object> redisTemplate) {
  20.         super(redisTemplate);
  21.     }
  22.     /**
  23.      * 左侧添加单个值
  24.      *
  25.      * @param key   键
  26.      * @param value 要添加的值
  27.      * @return 添加后的List长度
  28.      */
  29.     public Long leftPush(String key, Object value) {
  30.         return redisTemplate.opsForList().leftPush(key, value);
  31.     }
  32.     /**
  33.      * 左侧批量添加多个值(使用List参数方式)
  34.      *
  35.      * @param key      键
  36.      * @param dataList 要添加的值列表
  37.      * @param <V>      值类型
  38.      * @return 添加后的List长度,调用方可以忽略返回值
  39.      */
  40.     public <V> Long leftPushAll(String key, List<V> dataList) {
  41.         return redisTemplate.opsForList().leftPushAll(key, dataList.toArray());
  42.     }
  43.     /**
  44.      * 左侧批量添加多个值(使用Collection参数方式)
  45.      *
  46.      * @param key           键
  47.      * @param dataCollection 要添加的值集合
  48.      * @param <V>           值类型
  49.      * @return 添加后的List长度
  50.      */
  51.     public <V> Long leftPushAll(String key, Collection<V> dataCollection) {
  52.         return redisTemplate.opsForList().leftPushAll(key, dataCollection.toArray());
  53.     }
  54.     /**
  55.      * 右侧添加单个值
  56.      *
  57.      * @param key   键
  58.      * @param value 要添加的值
  59.      * @return 添加后的List长度
  60.      */
  61.     public Long rightPush(String key, Object value) {
  62.         return redisTemplate.opsForList().rightPush(key, value);
  63.     }
  64.     /**
  65.      * 右侧批量添加多个值(使用List参数方式)
  66.      *
  67.      * @param key      键
  68.      * @param dataList 要添加的值列表
  69.      * @param <V>      值类型
  70.      * @return 添加后的List长度
  71.      */
  72.     public <V> Long rightPushAll(String key, List<V> dataList) {
  73.         return redisTemplate.opsForList().rightPushAll(key, dataList.toArray());
  74.     }
  75.     /**
  76.      * 右侧批量添加多个值(使用Collection参数方式)
  77.      *
  78.      * @param key           键
  79.      * @param dataCollection 要添加的值集合
  80.      * @param <V>           值类型
  81.      * @return 添加后的List长度
  82.      */
  83.     public <V> Long rightPushAll(String key, Collection<V> dataCollection) {
  84.         return redisTemplate.opsForList().rightPushAll(key, dataCollection.toArray());
  85.     }
  86.     /**
  87.      * 根据值移除指定数量的匹配元素
  88.      *
  89.      * @param key   键
  90.      * @param count 要移除的元素数量
  91.      * @param value 要移除的值
  92.      * @return 移除的元素数量
  93.      */
  94.     public Long removeByValue(String key, long count, Object value) {
  95.         return redisTemplate.opsForList().remove(key, count, value);
  96.     }
  97.     /**
  98.      * 从右侧弹出元素并转换为指定类型
  99.      *
  100.      * @param key  键
  101.      * @param type 期望的返回值类型
  102.      * @param <T>  泛型,表示期望的返回类型
  103.      * @return 弹出并转换后的元素
  104.      */
  105.     public <T> T popRight(String key, Class<T> type) {
  106.         Object value = redisTemplate.opsForList().rightPop(key);
  107.         return convertValue(value, type);
  108.     }
  109.     /**
  110.      * 从左侧弹出元素并转换为指定类型
  111.      *
  112.      * @param key  键
  113.      * @param type 期望的返回值类型
  114.      * @param <T>  泛型,表示期望的返回类型
  115.      * @return 弹出并转换后的元素
  116.      */
  117.     public <T> T popLeft(String key, Class<T> type) {
  118.         Object value = redisTemplate.opsForList().leftPop(key);
  119.         return convertValue(value, type);
  120.     }
  121.     /**
  122.      * 根据索引设置List中的值
  123.      *
  124.      * @param key   键
  125.      * @param index 索引位置,从0开始
  126.      * @param value 设置的值
  127.      */
  128.     public void set(String key, final long index, Object value) {
  129.         redisTemplate.opsForList().set(key, index, value);
  130.     }
  131.     /**
  132.      * 获取List中的所有数据,并将每个元素转换为指定类型
  133.      *
  134.      * @param key  键
  135.      * @param type 要转换的值类型
  136.      * @param <T>  要转换的值类型
  137.      * @return 转换后的List
  138.      */
  139.     public <T> List<T> rangeAll(String key, Class<T> type) {
  140.         List<Object> range = redisTemplate.opsForList().range(key, 0, -1);
  141.         List<T> result = new ArrayList<>();
  142.         if (range != null) {
  143.             for (Object item : range) {
  144.                 result.add(convertValue(item, type));
  145.             }
  146.         }
  147.         return result;
  148.     }
  149.     /**
  150.      * 根据索引获取List中的元素并转换为指定类型
  151.      *
  152.      * @param key   键
  153.      * @param index 索引位置,从0开始
  154.      * @param type  期望的返回值类型
  155.      * @param <T>   泛型,表示期望的返回类型
  156.      * @return 转换后的元素
  157.      */
  158.     public <T> T getElementByIndex(String key, long index, Class<T> type) {
  159.         Object value = redisTemplate.opsForList().index(key, index);
  160.         return convertValue(value, type);
  161.     }
  162.     /**
  163.      * 获取List的长度
  164.      *
  165.      * @param key 键
  166.      * @return List的长度
  167.      */
  168.     public Long size(String key) {
  169.         return redisTemplate.opsForList().size(key);
  170.     }
  171. }
复制代码
4.RSet.java

  1. package com.sunxiansheng.redis.utils;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import java.util.HashSet;
  4. import java.util.Set;
  5. /**
  6. * Description: Redis的Set类型操作
  7. *
  8. * @Author sun
  9. * @Create 2024/11/14 14:50
  10. * @Version 1.0
  11. */
  12. public class RSet extends RBase {
  13.     /**
  14.      * 构造器给父类注入RedisTemplate
  15.      *
  16.      * @param redisTemplate RedisTemplate实例
  17.      */
  18.     public RSet(RedisTemplate<String, Object> redisTemplate) {
  19.         super(redisTemplate);
  20.     }
  21.     /**
  22.      * 添加一个元素
  23.      *
  24.      * @param key  键
  25.      * @param data 值
  26.      * @return 添加成功的个数
  27.      */
  28.     public Long add(String key, Object data) {
  29.         return redisTemplate.opsForSet().add(key, data);
  30.     }
  31.     /**
  32.      * 批量添加元素,并返回添加成功的个数
  33.      *
  34.      * @param key     键
  35.      * @param dataSet 值集合
  36.      * @param <T>     添加的元素类型
  37.      * @return 添加成功的个数
  38.      */
  39.     public <T> Long addBatch(String key, Set<T> dataSet) {
  40.         return redisTemplate.opsForSet().add(key, dataSet.toArray());
  41.     }
  42.     /**
  43.      * 移除特定的元素,并返回移除成功的个数
  44.      *
  45.      * @param key     键
  46.      * @param dataSet 要移除的元素集合
  47.      * @param <T>     要移除的元素类型
  48.      * @return 移除成功的个数
  49.      */
  50.     public <T> Long remove(String key, Set<T> dataSet) {
  51.         return redisTemplate.opsForSet().remove(key, dataSet.toArray());
  52.     }
  53.     /**
  54.      * 获取集合,并将每个元素转换为指定类型
  55.      *
  56.      * @param key  键
  57.      * @param type 集合中元素的目标类型
  58.      * @param <T>  元素的类型
  59.      * @return 转换后的集合
  60.      */
  61.     public <T> Set<T> members(String key, Class<T> type) {
  62.         Set<Object> members = redisTemplate.opsForSet().members(key);
  63.         Set<T> result = new HashSet<>();
  64.         if (members != null) {
  65.             for (Object member : members) {
  66.                 result.add(convertValue(member, type));
  67.             }
  68.         }
  69.         return result;
  70.     }
  71.     /**
  72.      * 判断集合中是否有该值
  73.      *
  74.      * @param key  键
  75.      * @param data 值
  76.      * @return 是否包含该值
  77.      */
  78.     public Boolean isMember(String key, Object data) {
  79.         return redisTemplate.opsForSet().isMember(key, data);
  80.     }
  81.     /**
  82.      * 获取set的长度
  83.      *
  84.      * @param key 键
  85.      * @return 集合的长度
  86.      */
  87.     public Long size(String key) {
  88.         return redisTemplate.opsForSet().size(key);
  89.     }
  90. }
复制代码
5.RHash.java

  1. package com.sunxiansheng.redis.utils;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import java.util.*;
  4. /**
  5. * Description: Redis的Hash类型操作
  6. *
  7. * @Author sun
  8. * @Create 2024/11/14 14:50
  9. * @Version 1.1
  10. */
  11. public class RHash extends RBase {
  12.     /**
  13.      * 构造器给父类注入RedisTemplate
  14.      *
  15.      * @param redisTemplate RedisTemplate实例
  16.      */
  17.     public RHash(RedisTemplate<String, Object> redisTemplate) {
  18.         super(redisTemplate);
  19.     }
  20.     /**
  21.      * 设置单个hash值
  22.      *
  23.      * @param key       key
  24.      * @param hashKey   hashKey
  25.      * @param hashValue hashValue
  26.      */
  27.     public void put(String key, String hashKey, Object hashValue) {
  28.         redisTemplate.opsForHash().put(key, hashKey, hashValue);
  29.     }
  30.     /**
  31.      * 设置多个hash值
  32.      *
  33.      * @param key key
  34.      * @param map map
  35.      */
  36.     public void putAll(String key, Map<String, ?> map) {
  37.         if (map == null || map.isEmpty()) {
  38.             throw new IllegalArgumentException("Map不能为空!");
  39.         }
  40.         redisTemplate.opsForHash().putAll(key, map);
  41.     }
  42.     /**
  43.      * 删除hash中的一些值
  44.      *
  45.      * @param key      key
  46.      * @param hashKeys hashKeys
  47.      * @return 删除的个数
  48.      */
  49.     public Long delete(String key, List<String> hashKeys) {
  50.         if (hashKeys == null || hashKeys.isEmpty()) {
  51.             return 0L;
  52.         }
  53.         return redisTemplate.opsForHash().delete(key, hashKeys.toArray());
  54.     }
  55.     /**
  56.      * 删除hash中的一个值
  57.      *
  58.      * @param key     key
  59.      * @param hashKey hashKey
  60.      * @return 删除的个数
  61.      */
  62.     public Long delete(String key, String hashKey) {
  63.         if (hashKey == null) {
  64.             return 0L;
  65.         }
  66.         return redisTemplate.opsForHash().delete(key, hashKey);
  67.     }
  68.     /**
  69.      * 获取单个hash值,并转换为指定类型
  70.      *
  71.      * @param key     key
  72.      * @param hashKey hashKey
  73.      * @param type    类型
  74.      * @param <T>     要转换的类型
  75.      * @return hash值
  76.      */
  77.     public <T> T getOneMapValue(String key, String hashKey, Class<T> type) {
  78.         if (hashKey == null) {
  79.             return null;
  80.         }
  81.         Object object = redisTemplate.opsForHash().get(key, hashKey);
  82.         return convertValue(object, type);
  83.     }
  84.     /**
  85.      * 获取多个hash值,并转换为指定类型
  86.      *
  87.      * @param key      Redis键
  88.      * @param hashKeys Hash键集合
  89.      * @param type     转换的目标类型
  90.      * @param <T>      返回的泛型类型
  91.      * @return 转换后的Hash对象集合
  92.      */
  93.     public <T> List<T> getMultiMapValue(String key, Collection<String> hashKeys, Class<T> type) {
  94.         if (hashKeys == null || hashKeys.isEmpty()) {
  95.             return Collections.emptyList();
  96.         }
  97.         Collection<Object> keys = new ArrayList<>(hashKeys);
  98.         List<Object> objects = redisTemplate.opsForHash().multiGet(key, keys);
  99.         List<T> result = new ArrayList<>();
  100.         for (Object obj : objects) {
  101.             result.add(convertValue(obj, type));
  102.         }
  103.         return result;
  104.     }
  105.     /**
  106.      * 获取所有键值对,并将其转换为指定类型
  107.      *
  108.      * @param key  键
  109.      * @param type 返回值的类型
  110.      * @param <T>  值类型
  111.      * @return 转换后的Map,键为String类型,值为T类型
  112.      */
  113.     public <T> Map<String, T> getAll(String key, Class<T> type) {
  114.         Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
  115.         if (entries.isEmpty()) {
  116.             return Collections.emptyMap();
  117.         }
  118.         Map<String, T> result = new HashMap<>();
  119.         for (Map.Entry<Object, Object> entry : entries.entrySet()) {
  120.             if (entry.getKey() instanceof String) {
  121.                 String strKey = (String) entry.getKey();
  122.                 T value = convertValue(entry.getValue(), type);
  123.                 result.put(strKey, value);
  124.             } else {
  125.                 throw new ClassCastException("Redis中Hash的键不是String类型:实际类型为 " + entry.getKey().getClass().getName());
  126.             }
  127.         }
  128.         return result;
  129.     }
  130.     /**
  131.      * 判断hash中是否存在某个键
  132.      *
  133.      * @param key     key
  134.      * @param hashKey hashKey
  135.      * @return 是否存在
  136.      */
  137.     public Boolean hasHashKey(String key, String hashKey) {
  138.         if (hashKey == null) {
  139.             return false;
  140.         }
  141.         return redisTemplate.opsForHash().hasKey(key, hashKey);
  142.     }
  143. }
复制代码
6.RSortedSet.java

  1. package com.sunxiansheng.redis.utils;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import org.springframework.data.redis.core.ZSetOperations;
  4. import java.util.HashSet;
  5. import java.util.Set;
  6. import java.util.TreeSet;
  7. /**
  8. * Description: Redis的ZSet类型操作
  9. *
  10. * @Author sun
  11. * @Create 2024/11/14 14:50
  12. * @Version 1.0
  13. */
  14. public class RSortedSet extends RBase {
  15.     /**
  16.      * 构造器给父类注入RedisTemplate
  17.      *
  18.      * @param redisTemplate RedisTemplate实例
  19.      */
  20.     public RSortedSet(RedisTemplate<String, Object> redisTemplate) {
  21.         super(redisTemplate);
  22.     }
  23.     /**
  24.      * 添加一个元素,并设置分数
  25.      *
  26.      * @param key   键
  27.      * @param data  元素
  28.      * @param score 分数
  29.      * @return 是否添加成功,成功返回true
  30.      */
  31.     public Boolean add(String key, Object data, double score) {
  32.         return redisTemplate.opsForZSet().add(key, data, score);
  33.     }
  34.     /**
  35.      * 自定义的数据分数类型,用于批量添加元素
  36.      *
  37.      * @param <T> 元素的类型
  38.      */
  39.     public static class DataScore<T> {
  40.         /**
  41.          * 数据
  42.          */
  43.         private T data;
  44.         /**
  45.          * 分数
  46.          */
  47.         private Double score;
  48.         public DataScore() {
  49.         }
  50.         public DataScore(T data, Double score) {
  51.             this.data = data;
  52.             this.score = score;
  53.         }
  54.         public T getData() {
  55.             return data;
  56.         }
  57.         public void setData(T data) {
  58.             this.data = data;
  59.         }
  60.         public Double getScore() {
  61.             return score;
  62.         }
  63.         public void setScore(Double score) {
  64.             this.score = score;
  65.         }
  66.     }
  67.     /**
  68.      * 批量添加元素,并设置分数
  69.      *
  70.      * @param key        键
  71.      * @param dataScores 自定义数据结构集合,包含元素及分数
  72.      * @param <T>        元素的类型
  73.      * @return 添加成功的元素数量
  74.      */
  75.     public <T> Long addBatch(String key, Set<DataScore<T>> dataScores) {
  76.         // 将 Set<DataScore<T>> 转换为 Set<ZSetOperations.TypedTuple<Object>>
  77.         Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>();
  78.         for (DataScore<T> dataScore : dataScores) {
  79.             tuples.add(new ZSetOperations.TypedTuple<Object>() {
  80.                 @Override
  81.                 public Object getValue() {
  82.                     return dataScore.getData(); // 调用 getData 方法
  83.                 }
  84.                 @Override
  85.                 public Double getScore() {
  86.                     return dataScore.getScore();
  87.                 }
  88.                 /**
  89.                  * 比较器,从大到小排序
  90.                  */
  91.                 @Override
  92.                 public int compareTo(ZSetOperations.TypedTuple<Object> o) {
  93.                     return Double.compare(o.getScore(), this.getScore());
  94.                 }
  95.             });
  96.         }
  97.         // 添加到 Redis 的 ZSet
  98.         return redisTemplate.opsForZSet().add(key, tuples);
  99.     }
  100.     /**
  101.      * 移除特定的元素
  102.      *
  103.      * @param key     键
  104.      * @param dataSet 要移除的元素集合
  105.      * @param <T>     元素类型
  106.      * @return 移除成功的元素数量
  107.      */
  108.     public <T> Long remove(String key, Set<T> dataSet) {
  109.         return redisTemplate.opsForZSet().remove(key, dataSet.toArray());
  110.     }
  111.     /**
  112.      * 删除指定分数范围的元素
  113.      *
  114.      * @param key 键
  115.      * @param min 最小分数
  116.      * @param max 最大分数
  117.      * @return 删除成功的元素数量
  118.      */
  119.     public Long removeRangeByScore(String key, double min, double max) {
  120.         return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
  121.     }
  122.     /**
  123.      * 根据delta值调整指定元素的分数
  124.      *
  125.      * @param key   键
  126.      * @param data  元素
  127.      * @param delta 增加或减少的分数值
  128.      * @return 调整后的分数
  129.      */
  130.     public Double changeByDelta(String key, Object data, double delta) {
  131.         return redisTemplate.opsForZSet().incrementScore(key, data, delta);
  132.     }
  133.     /**
  134.      * 获取全部ZSet元素(分数从大到小),并将值转换为指定类型
  135.      *
  136.      * @param key  Redis键
  137.      * @param type 元素的目标类型
  138.      * @param <T>  元素类型
  139.      * @return 转换后的ZSet集合,包含分值和对应的值
  140.      */
  141.     public <T> Set<ZSetOperations.TypedTuple<T>> reverseRangeWithScores(String key, Class<T> type) {
  142.         // 获取 Redis 中的 ZSet 数据
  143.         Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, -1);
  144.         // 使用 TreeSet 并提供自定义比较器,从大到小排序
  145.         Set<ZSetOperations.TypedTuple<T>> result = new TreeSet<>((a, b) -> Double.compare(b.getScore(), a.getScore()));
  146.         // 遍历并进行类型转换
  147.         if (typedTuples != null) {
  148.             for (ZSetOperations.TypedTuple<Object> tuple : typedTuples) {
  149.                 T value = convertValue(tuple.getValue(), type);
  150.                 Double score = tuple.getScore();
  151.                 result.add(new ZSetOperations.TypedTuple<T>() {
  152.                     @Override
  153.                     public T getValue() {
  154.                         return value;
  155.                     }
  156.                     @Override
  157.                     public Double getScore() {
  158.                         return score;
  159.                     }
  160.                     /**
  161.                      * 比较器,从大到小排序
  162.                      */
  163.                     @Override
  164.                     public int compareTo(ZSetOperations.TypedTuple<T> o) {
  165.                         return Double.compare(o.getScore(), this.getScore());
  166.                     }
  167.                 });
  168.             }
  169.         }
  170.         return result;
  171.     }
  172.     /**
  173.      * 获取指定元素的分数
  174.      *
  175.      * @param key  键
  176.      * @param data 元素
  177.      * @return 元素的分数
  178.      */
  179.     public Double score(String key, Object data) {
  180.         return redisTemplate.opsForZSet().score(key, data);
  181.     }
  182.     /**
  183.      * 获取指定元素的排名(从大到小)
  184.      *
  185.      * @param key  键
  186.      * @param data 元素
  187.      * @return 排名(从0开始)
  188.      */
  189.     public Long reverseRank(String key, Object data) {
  190.         return redisTemplate.boundZSetOps(key).reverseRank(data);
  191.     }
  192.     /**
  193.      * 获取ZSet中的元素总数
  194.      *
  195.      * @param key 键
  196.      * @return 元素个数
  197.      */
  198.     public Long zCard(String key) {
  199.         return redisTemplate.opsForZSet().zCard(key);
  200.     }
  201.     /**
  202.      * 获取指定分数范围内的元素数量
  203.      *
  204.      * @param key 键
  205.      * @param min 最小分数
  206.      * @param max 最大分数
  207.      * @return 元素数量
  208.      */
  209.     public Long count(String key, double min, double max) {
  210.         return redisTemplate.opsForZSet().count(key, min, max);
  211.     }
  212. }
复制代码
4.测试

1.创建测试模块


2.引入依靠

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.     <modelVersion>4.0.0</modelVersion>
  6.     <parent>
  7.         <groupId>com.sunxiansheng</groupId>
  8.         <artifactId>sunrays-demo</artifactId>
  9.         <version>1.0</version>
  10.     </parent>
  11.     <artifactId>common-redis-starter-demo</artifactId>
  12.     <dependencies>
  13.         <!-- 引入自定义的 common-redis-starter -->
  14.         <dependency>
  15.             <groupId>com.sunxiansheng</groupId>
  16.             <artifactId>common-redis-starter</artifactId>
  17.             <version>1.0</version>
  18.         </dependency>
  19.         <!-- 引入自定义的 common-log4j2-starter -->
  20.         <dependency>
  21.             <groupId>com.sunxiansheng</groupId>
  22.             <artifactId>common-log4j2-starter</artifactId>
  23.             <version>1.0</version>
  24.         </dependency>
  25.         <!-- 引入自定义的 common-web-starter -->
  26.         <dependency>
  27.             <groupId>com.sunxiansheng</groupId>
  28.             <artifactId>common-web-starter</artifactId>
  29.             <version>1.0</version>
  30.         </dependency>
  31.     </dependencies>
  32. </project>
复制代码
3.启动类

  1. package com.sunxiansheng.redis;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. /**
  5. * Description: Redis启动类
  6. *
  7. * @Author sun
  8. * @Create 2024/11/15 20:56
  9. * @Version 1.0
  10. */
  11. @SpringBootApplication
  12. public class RedisApplication {
  13.     public static void main(String[] args) {
  14.         SpringApplication.run(RedisApplication.class, args);
  15.     }
  16. }
复制代码

4.编写application.yml

  1. spring:
  2.   redis:
  3.     host:  # Redis服务器地址
  4.     port:  # Redis服务器端口
  5.     password:  # Redis服务器密码
  6.     database: 0 # 默认数据库为0号
  7.     timeout: 1800000 # 连接超时时间是1800秒
  8.     lettuce:
  9.       pool:
  10.         max-active: 20 # 最大活跃连接数,使用负值表示没有限制
  11.         max-wait: -1 # 最大等待时间,单位为毫秒,使用负值表示没有限制
  12.         max-idle: 10 # 最大空闲连接数
  13.         min-idle: 0 # 最小空闲连接数
复制代码
5.测试

1.RStringController.java

  1. package com.sunxiansheng.redis.controller;
  2. import com.sunxiansheng.redis.utils.RString;
  3. import org.springframework.web.bind.annotation.*;
  4. import javax.annotation.Resource;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * Description: 测试 RString 工具类的 Controller
  8. *
  9. * @Author sun
  10. * @Create 2024/11/14 15:20
  11. * @Version 1.0
  12. */
  13. @RestController
  14. @RequestMapping("/rstring")
  15. public class RStringController {
  16.     @Resource
  17.     private RString rString;
  18.     /**
  19.      * 设置缓存值
  20.      */
  21.     @PostMapping("/set")
  22.     public String set(@RequestParam String key, @RequestParam Long value) {
  23.         rString.set(key, value);
  24.         return "Value set successfully!";
  25.     }
  26.     /**
  27.      * 设置缓存值并设置过期时间
  28.      */
  29.     @PostMapping("/setWithExpire")
  30.     public String setWithExpire(@RequestParam String key,
  31.                                 @RequestParam Long value,
  32.                                 @RequestParam long timeout) {
  33.         rString.setWithExpire(key, value, timeout);
  34.         return "Value set with expiration successfully!";
  35.     }
  36.     /**
  37.      * 设置缓存值并设置过期时间(自定义时间单位)
  38.      */
  39.     @PostMapping("/setWithExpireUnit")
  40.     public String setWithExpireUnit(@RequestParam String key,
  41.                                     @RequestParam Long value,
  42.                                     @RequestParam long timeout) {
  43.         rString.setWithExpire(key, value, timeout, TimeUnit.DAYS);
  44.         return "Value set with custom expiration successfully!";
  45.     }
  46.     /**
  47.      * 设置缓存值,如果key不存在,则设置成功
  48.      */
  49.     @PostMapping("/setIfAbsent")
  50.     public String setIfAbsent(@RequestParam String key,
  51.                               @RequestParam Long value,
  52.                               @RequestParam long timeout) {
  53.         boolean result = rString.setIfAbsent(key, value, timeout);
  54.         return result ? "Value set successfully!" : "Key already exists!";
  55.     }
  56.     /**
  57.      * 获取缓存值
  58.      */
  59.     @GetMapping("/get")
  60.     public Long get(@RequestParam String key) {
  61.         return rString.get(key, Long.class);
  62.     }
  63.     /**
  64.      * 获取缓存值并设置新值
  65.      */
  66.     @PostMapping("/getAndSet")
  67.     public Long getAndSet(@RequestParam String key, @RequestParam Long value) {
  68.         return rString.getAndSet(key, value, Long.class);
  69.     }
  70.     /**
  71.      * 根据 delta 值调整缓存中的数值
  72.      */
  73.     @PostMapping("/changeByDelta")
  74.     public Long changeByDelta(@RequestParam String key, @RequestParam long delta) {
  75.         return rString.changeByDelta(key, delta);
  76.     }
  77. }
复制代码
2.RListController.java

  1. package com.sunxiansheng.redis.controller;
  2. import com.sunxiansheng.redis.utils.RList;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. import java.util.List;
  9. /**
  10. * 测试 RList 工具类的 Controller
  11. *
  12. * @Author sun
  13. * @Create 2024/11/14 16:00
  14. * @Version 1.0
  15. */
  16. @RestController
  17. @RequestMapping("/rlist")
  18. public class RListController {
  19.     @Autowired
  20.     private RList rList;
  21.     /**
  22.      * 左侧添加单个值
  23.      */
  24.     @PostMapping("/leftPush")
  25.     public String leftPush(@RequestParam String key, @RequestBody User user) {
  26.         rList.leftPush(key, user);
  27.         return "User added to the left of the list.";
  28.     }
  29.     /**
  30.      * 左侧批量添加多个值
  31.      */
  32.     @PostMapping("/leftPushAll")
  33.     public String leftPushAll(@RequestParam String key, @RequestBody List<User> users) {
  34.         rList.leftPushAll(key, users);
  35.         return "Users added to the left of the list.";
  36.     }
  37.     /**
  38.      * 右侧添加单个值
  39.      */
  40.     @PostMapping("/rightPush")
  41.     public String rightPush(@RequestParam String key, @RequestBody User user) {
  42.         rList.rightPush(key, user);
  43.         return "User added to the right of the list.";
  44.     }
  45.     /**
  46.      * 右侧批量添加多个值
  47.      */
  48.     @PostMapping("/rightPushAll")
  49.     public String rightPushAll(@RequestParam String key, @RequestBody List<User> users) {
  50.         rList.rightPushAll(key, users);
  51.         return "Users added to the right of the list.";
  52.     }
  53.     /**
  54.      * 根据索引设置List中的值
  55.      */
  56.     @PutMapping("/set")
  57.     public String set(@RequestParam String key, @RequestParam int index, @RequestBody User user) {
  58.         rList.set(key, index, user);
  59.         return "User updated at index " + index;
  60.     }
  61.     /**
  62.      * 获取List中的所有数据
  63.      */
  64.     @GetMapping("/rangeAll")
  65.     public List<User> rangeAll(@RequestParam String key) {
  66.         return rList.rangeAll(key, User.class);
  67.     }
  68.     /**
  69.      * 根据索引获取List中的元素
  70.      */
  71.     @GetMapping("/getElementByIndex")
  72.     public User getElementByIndex(@RequestParam String key, @RequestParam int index) {
  73.         return rList.getElementByIndex(key, index, User.class);
  74.     }
  75.     /**
  76.      * 获取List的长度
  77.      */
  78.     @GetMapping("/size")
  79.     public Long size(@RequestParam String key) {
  80.         return rList.size(key);
  81.     }
  82.     /**
  83.      * 从右侧弹出元素
  84.      */
  85.     @DeleteMapping("/popRight")
  86.     public User popRight(@RequestParam String key) {
  87.         return rList.popRight(key, User.class);
  88.     }
  89.     /**
  90.      * 从左侧弹出元素
  91.      */
  92.     @DeleteMapping("/popLeft")
  93.     public User popLeft(@RequestParam String key) {
  94.         return rList.popLeft(key, User.class);
  95.     }
  96.     /**
  97.      * 根据值移除指定数量的匹配元素
  98.      */
  99.     @DeleteMapping("/removeByValue")
  100.     public String removeByValue(@RequestParam String key, @RequestParam int count, @RequestBody User user) {
  101.         Long removedCount = rList.removeByValue(key, count, user);
  102.         return removedCount + " matching users removed.";
  103.     }
  104. }
  105. /**
  106. * 简单的自定义类型 User
  107. *
  108. * @Author sun
  109. * @Create 2024/11/14 15:50
  110. * @Version 1.0
  111. */
  112. @NoArgsConstructor
  113. @Data
  114. @AllArgsConstructor
  115. class User implements java.io.Serializable {
  116.     private String id;
  117.     private String name;
  118. }
复制代码
3.RSetController.java

  1. package com.sunxiansheng.redis.controller;
  2. import com.sunxiansheng.redis.utils.RSet;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. import java.io.Serializable;
  9. import java.util.Set;
  10. /**
  11. * Description: RSet的测试Controller
  12. *
  13. * @Author sun
  14. * @Create 2024/11/15
  15. * @Version 1.0
  16. */
  17. @RestController
  18. @RequestMapping("/rset")
  19. public class RSetController {
  20.     @Autowired
  21.     private RSet rSet;
  22.     /**
  23.      * 静态内部类表示简单的自定义对象
  24.      */
  25.     @Data
  26.     @NoArgsConstructor
  27.     @AllArgsConstructor
  28.     public static class Element implements Serializable {
  29.         private Long id;
  30.         private String name;
  31.     }
  32.     /**
  33.      * 添加一个元素
  34.      */
  35.     @PostMapping("/add")
  36.     public Long add(@RequestParam String key, @RequestBody Element element) {
  37.         return rSet.add(key, element);
  38.     }
  39.     /**
  40.      * 批量添加元素
  41.      */
  42.     @PostMapping("/addBatch")
  43.     public Long addBatch(@RequestParam String key, @RequestBody Set<Element> elements) {
  44.         return rSet.addBatch(key, elements);
  45.     }
  46.     /**
  47.      * 移除元素
  48.      */
  49.     @PostMapping("/remove")
  50.     public Long remove(@RequestParam String key, @RequestBody Set<Element> elements) {
  51.         return rSet.remove(key, elements);
  52.     }
  53.     /**
  54.      * 获取集合
  55.      */
  56.     @GetMapping("/members")
  57.     public Set<Element> members(@RequestParam String key) {
  58.         return rSet.members(key, Element.class);
  59.     }
  60.     /**
  61.      * 判断是否包含某元素
  62.      */
  63.     @GetMapping("/isMember")
  64.     public Boolean isMember(@RequestParam String key, @RequestBody Element element) {
  65.         return rSet.isMember(key, element);
  66.     }
  67.     /**
  68.      * 获取集合大小
  69.      */
  70.     @GetMapping("/size")
  71.     public Long size(@RequestParam String key) {
  72.         return rSet.size(key);
  73.     }
  74. }
复制代码
4.RHashController.java

  1. package com.sunxiansheng.redis.controller;
  2. import com.sunxiansheng.redis.utils.RHash;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import org.springframework.web.bind.annotation.*;
  7. import java.util.*;
  8. @RestController
  9. @RequestMapping("/rhash")
  10. public class RHashController {
  11.     private final RHash rHash;
  12.     public RHashController(RHash rHash) {
  13.         this.rHash = rHash;
  14.     }
  15.     @NoArgsConstructor
  16.     @AllArgsConstructor
  17.     @Data
  18.     public static class User {
  19.         private Long id;
  20.         private String name;
  21.         private Integer age;
  22.     }
  23.     /**
  24.      * 设置单个hash值
  25.      */
  26.     @PostMapping("/put")
  27.     public void put(@RequestParam String key, @RequestParam String hashKey, @RequestBody User user) {
  28.         rHash.put(key, hashKey, user);
  29.     }
  30.     /**
  31.      * 设置多个hash值
  32.      */
  33.     @PostMapping("/putAll")
  34.     public void putAll(@RequestParam String key, @RequestBody Map<String, User> userMap) {
  35.         rHash.putAll(key, userMap);
  36.     }
  37.     /**
  38.      * 删除hash中的多个值
  39.      */
  40.     @DeleteMapping("/deleteMultiple")
  41.     public Long deleteMultiple(@RequestParam String key, @RequestBody List<String> hashKeys) {
  42.         return rHash.delete(key, hashKeys);
  43.     }
  44.     /**
  45.      * 删除hash中的单个值
  46.      */
  47.     @DeleteMapping("/deleteSingle")
  48.     public Long deleteSingle(@RequestParam String key, @RequestParam String hashKey) {
  49.         return rHash.delete(key, hashKey);
  50.     }
  51.     /**
  52.      * 获取单个hash值并转换为指定类型
  53.      */
  54.     @GetMapping("/getOne")
  55.     public User getOneMapValue(@RequestParam String key, @RequestParam String hashKey) {
  56.         return rHash.getOneMapValue(key, hashKey, User.class);
  57.     }
  58.     /**
  59.      * 获取多个hash值并转换为指定类型
  60.      */
  61.     @GetMapping("/getMulti")
  62.     public List<User> getMultiMapValue(@RequestParam String key, @RequestBody List<String> hashKeys) {
  63.         return rHash.getMultiMapValue(key, hashKeys, User.class);
  64.     }
  65.     /**
  66.      * 获取所有键值对并转换为指定类型
  67.      */
  68.     @GetMapping("/getAll")
  69.     public Map<String, User> getAll(@RequestParam String key) {
  70.         return rHash.getAll(key, User.class);
  71.     }
  72.     /**
  73.      * 判断hash中是否存在某个键
  74.      */
  75.     @GetMapping("/hasHashKey")
  76.     public Boolean hasHashKey(@RequestParam String key, @RequestParam String hashKey) {
  77.         return rHash.hasHashKey(key, hashKey);
  78.     }
  79. }
复制代码
5.RSortedSetController.java

  1. package com.sunxiansheng.redis.controller;
  2. import com.sunxiansheng.redis.utils.RSortedSet;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.redis.core.ZSetOperations;
  8. import org.springframework.web.bind.annotation.*;
  9. import java.util.Set;
  10. /**
  11. * Description: 测试 RSortedSet 工具类
  12. *
  13. * @Author sun
  14. * @Create 2024/11/16
  15. * @Version 1.0
  16. */
  17. @RestController
  18. @RequestMapping("/rsortedset")
  19. public class RSortedSetController {
  20.     @Autowired
  21.     private RSortedSet rSortedSet;
  22.     // 自定义类型
  23.     @Data
  24.     @NoArgsConstructor
  25.     @AllArgsConstructor
  26.     public static class CustomValue {
  27.         private Long id;
  28.         private String name;
  29.     }
  30.     @PostMapping("/add")
  31.     public Boolean add(@RequestParam String key, @RequestBody CustomValue value, @RequestParam double score) {
  32.         return rSortedSet.add(key, value, score);
  33.     }
  34.     @PostMapping("/addBatch")
  35.     public Long addBatch(@RequestParam String key, @RequestBody Set<RSortedSet.DataScore<CustomValue>> dataScores) {
  36.         return rSortedSet.addBatch(key, dataScores);
  37.     }
  38.     @PostMapping("/remove")
  39.     public Long remove(@RequestParam String key, @RequestBody Set<CustomValue> values) {
  40.         return rSortedSet.remove(key, values);
  41.     }
  42.     @PostMapping("/removeRangeByScore")
  43.     public Long removeRangeByScore(@RequestParam String key, @RequestParam double min, @RequestParam double max) {
  44.         return rSortedSet.removeRangeByScore(key, min, max);
  45.     }
  46.     @PostMapping("/changeByDelta")
  47.     public Double changeByDelta(@RequestParam String key, @RequestBody CustomValue value, @RequestParam double delta) {
  48.         return rSortedSet.changeByDelta(key, value, delta);
  49.     }
  50.     @GetMapping("/reverseRangeWithScores")
  51.     public Set<ZSetOperations.TypedTuple<CustomValue>> reverseRangeWithScores(@RequestParam String key) {
  52.         return rSortedSet.reverseRangeWithScores(key, CustomValue.class);
  53.     }
  54.     @GetMapping("/score")
  55.     public Double score(@RequestParam String key, @RequestBody CustomValue value) {
  56.         return rSortedSet.score(key, value);
  57.     }
  58.     @GetMapping("/reverseRank")
  59.     public Long reverseRank(@RequestParam String key, @RequestBody CustomValue value) {
  60.         return rSortedSet.reverseRank(key, value);
  61.     }
  62.     @GetMapping("/zCard")
  63.     public Long zCard(@RequestParam String key) {
  64.         return rSortedSet.zCard(key);
  65.     }
  66.     @GetMapping("/count")
  67.     public Long count(@RequestParam String key, @RequestParam double min, @RequestParam double max) {
  68.         return rSortedSet.count(key, min, max);
  69.     }
  70. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

勿忘初心做自己

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表