common-redis-starter
1.功能介绍
1. 快捷操作
- 支持五大基础数据类型(String、Hash、List、Set、SortedSet)的全面操作。
- 常用功能包括新增、删除、修改、查询及批量操作,使用便捷。
2. 灵活性
- 提供自定义缓存键名生成方法,支持默认分隔符(
:)
及自定义分隔符的拼接。 - 通过 Lua 脚本支持原子操作,提升操作性能。
3. 数据安全性
- 缓存数据采用 JSON 序列化存储,自动保留类型信息,确保数据在反序列化时的准确性。
- 完善的类型转换支持,提供类型安全的 Redis 操作。
4. 高效的管理
- 支持对键设置过期时间、延长有效期、批量删除等操作。
- 针对不同场景,提供丰富的类型专用方法,如:批量获取、排序操作、分数范围查询等。
5.丰富的操作功能
String 类型
- 快速设置键值。
- 设置带过期时间的缓存。
- 支持条件操作(如键不存在时才设置值)。
Hash 类型
- 单值、多值的添加与删除。
- 获取单个值、多个值及完整键值对。
- 支持键值对的批量操作。
List 类型
- 左/右添加与弹出。
- 根据索引操作列表元素。
- 支持获取指定范围及完整列表内容。
Set 类型
- 元素的添加、删除及批量操作。
- 集合长度查询及随机元素获取。
- 检查集合是否包含某个元素。
SortedSet 类型
- 添加元素及分数更新。
- 获取指定分数范围的元素及排序结果。
- 支持获取元素排名及分数。
2.配置示例
yaml
spring:
redis:
host: ${REDIS_HOST} # Redis服务器地址 ip
port: ${REDIS_PORT} # Redis服务器端口
password: ${REDIS_PASSWORD} # Redis服务器密码
3.案例演示
1.创建模块
2.目录结构
3.pom.xml
1.基本配置
xml
<!-- 通过properties来指定版本号 -->
<properties>
<!-- 指定编译版本 -->
<java.version>1.8</java.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 指定Sunrays-Framework的版本 -->
<sunrays.version>1.0.0</sunrays.version>
</properties>
<dependencyManagement>
<!-- 使用sunrays-dependencies来管理依赖,则依赖无需加版本号 -->
<dependencies>
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>sunrays-dependencies</artifactId>
<version>${sunrays.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.引入依赖
xml
<dependencies>
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-redis-starter</artifactId>
</dependency>
<!-- common-log4j2-starter 是必须引入的!!! -->
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-log4j2-starter</artifactId>
</dependency>
<!-- 用来测试的Web模块 -->
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-web-starter</artifactId>
</dependency>
<!-- env模块确保数据安全,可以不引入 -->
<dependency>
<groupId>cn.sunxiansheng</groupId>
<artifactId>common-env-starter</artifactId>
</dependency>
</dependencies>
4.application.yml 配置日志根目录、.env文件的绝对路径以及Redis
yaml
sun-rays:
log4j2:
home: /Users/sunxiansheng/IdeaProjects/sunrays-framework-demo/common-redis-starter-demo/logs # 日志根目录(默认./logs)
env:
path: /Users/sunxiansheng/IdeaProjects/sunrays-framework-demo/common-redis-starter-demo # .env文件的绝对路径
spring:
redis:
host: ${REDIS_HOST} # Redis主机
port: ${REDIS_PORT} # Redis服务器端口
password: ${REDIS_PASSWORD} # Redis服务器密码
5..env 配置Redis的信息
properties
REDIS_HOST=Redis主机
REDIS_PORT=Redis服务器端口
REDIS_PASSWORD=Redis服务器密码
6.测试的Controller
1.RHashController.java
java
package cn.sunxiansheng.redis.controller;
import cn.sunxiansheng.redis.utils.RHash;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/rhash")
public class RHashController {
private final RHash rHash;
public RHashController(RHash rHash) {
this.rHash = rHash;
}
@NoArgsConstructor
@AllArgsConstructor
@Data
public static class User {
private Long id;
private String name;
private Integer age;
}
/**
* 设置单个hash值
*/
@PostMapping("/put")
public void put(@RequestParam String key, @RequestParam String hashKey, @RequestBody User user) {
rHash.put(key, hashKey, user);
}
/**
* 设置多个hash值
*/
@PostMapping("/putAll")
public void putAll(@RequestParam String key, @RequestBody Map<String, User> userMap) {
rHash.putAll(key, userMap);
}
/**
* 删除hash中的多个值
*/
@DeleteMapping("/deleteMultiple")
public Long deleteMultiple(@RequestParam String key, @RequestBody List<String> hashKeys) {
return rHash.delete(key, hashKeys);
}
/**
* 删除hash中的单个值
*/
@DeleteMapping("/deleteSingle")
public Long deleteSingle(@RequestParam String key, @RequestParam String hashKey) {
return rHash.delete(key, hashKey);
}
/**
* 获取单个hash值并转换为指定类型
*/
@GetMapping("/getOne")
public User getOneMapValue(@RequestParam String key, @RequestParam String hashKey) {
return rHash.getOneMapValue(key, hashKey, User.class);
}
/**
* 获取多个hash值并转换为指定类型
*/
@GetMapping("/getMulti")
public List<User> getMultiMapValue(@RequestParam String key, @RequestBody List<String> hashKeys) {
return rHash.getMultiMapValue(key, hashKeys, User.class);
}
/**
* 获取所有键值对并转换为指定类型
*/
@GetMapping("/getAll")
public Map<String, User> getAll(@RequestParam String key) {
return rHash.getAll(key, User.class);
}
/**
* 判断hash中是否存在某个键
*/
@GetMapping("/hasHashKey")
public Boolean hasHashKey(@RequestParam String key, @RequestParam String hashKey) {
return rHash.hasHashKey(key, hashKey);
}
}
2.RSetController.java
java
package cn.sunxiansheng.redis.controller;
import cn.sunxiansheng.redis.utils.RSet;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.Set;
/**
* Description: RSet的测试Controller
*
* @Author sun
* @Create 2024/11/15
* @Version 1.0
*/
@RestController
@RequestMapping("/rset")
public class RSetController {
@Autowired
private RSet rSet;
/**
* 静态内部类表示简单的自定义对象
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Element implements Serializable {
private Long id;
private String name;
}
/**
* 添加一个元素
*/
@PostMapping("/add")
public Long add(@RequestParam String key, @RequestBody Element element) {
return rSet.add(key, element);
}
/**
* 批量添加元素
*/
@PostMapping("/addBatch")
public Long addBatch(@RequestParam String key, @RequestBody Set<Element> elements) {
return rSet.addBatch(key, elements);
}
/**
* 移除元素
*/
@PostMapping("/remove")
public Long remove(@RequestParam String key, @RequestBody Set<Element> elements) {
return rSet.remove(key, elements);
}
/**
* 获取集合
*/
@GetMapping("/members")
public Set<Element> members(@RequestParam String key) {
return rSet.members(key, Element.class);
}
/**
* 判断是否包含某元素
*/
@GetMapping("/isMember")
public Boolean isMember(@RequestParam String key, @RequestBody Element element) {
return rSet.isMember(key, element);
}
/**
* 获取集合大小
*/
@GetMapping("/size")
public Long size(@RequestParam String key) {
return rSet.size(key);
}
}
3.RSortedSetController.java
java
package cn.sunxiansheng.redis.controller;
import cn.sunxiansheng.redis.utils.RSortedSet;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
/**
* Description: 测试 RSortedSet 工具类
*
* @Author sun
* @Create 2024/11/16
* @Version 1.0
*/
@RestController
@RequestMapping("/rsortedset")
public class RSortedSetController {
@Autowired
private RSortedSet rSortedSet;
// 自定义类型
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class CustomValue {
private Long id;
private String name;
}
@PostMapping("/add")
public Boolean add(@RequestParam String key, @RequestBody CustomValue value, @RequestParam double score) {
return rSortedSet.add(key, value, score);
}
@PostMapping("/addBatch")
public Long addBatch(@RequestParam String key, @RequestBody Set<RSortedSet.DataScore<CustomValue>> dataScores) {
return rSortedSet.addBatch(key, dataScores);
}
@PostMapping("/remove")
public Long remove(@RequestParam String key, @RequestBody Set<CustomValue> values) {
return rSortedSet.remove(key, values);
}
@PostMapping("/removeRangeByScore")
public Long removeRangeByScore(@RequestParam String key, @RequestParam double min, @RequestParam double max) {
return rSortedSet.removeRangeByScore(key, min, max);
}
@PostMapping("/changeByDelta")
public Double changeByDelta(@RequestParam String key, @RequestBody CustomValue value, @RequestParam double delta) {
return rSortedSet.changeByDelta(key, value, delta);
}
@GetMapping("/reverseRangeWithScores")
public Set<ZSetOperations.TypedTuple<CustomValue>> reverseRangeWithScores(@RequestParam String key) {
return rSortedSet.reverseRangeWithScores(key, CustomValue.class);
}
@GetMapping("/score")
public Double score(@RequestParam String key, @RequestBody CustomValue value) {
return rSortedSet.score(key, value);
}
@GetMapping("/reverseRank")
public Long reverseRank(@RequestParam String key, @RequestBody CustomValue value) {
return rSortedSet.reverseRank(key, value);
}
@GetMapping("/zCard")
public Long zCard(@RequestParam String key) {
return rSortedSet.zCard(key);
}
@GetMapping("/count")
public Long count(@RequestParam String key, @RequestParam double min, @RequestParam double max) {
return rSortedSet.count(key, min, max);
}
}
4.RStringController.java
java
package cn.sunxiansheng.redis.controller;
import cn.sunxiansheng.redis.utils.RString;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* Description: 测试 RString 工具类的 Controller
*
* @Author sun
* @Create 2024/11/14 15:20
* @Version 1.0
*/
@RestController
@RequestMapping("/rstring")
public class RStringController {
@Resource
private RString rString;
/**
* 设置缓存值
*/
@PostMapping("/set")
public String set(@RequestParam String key, @RequestParam Long value) {
rString.set(key, value);
return "Value set successfully!";
}
/**
* 设置缓存值并设置过期时间
*/
@PostMapping("/setWithExpire")
public String setWithExpire(@RequestParam String key,
@RequestParam Long value,
@RequestParam long timeout) {
rString.setWithExpire(key, value, timeout);
return "Value set with expiration successfully!";
}
/**
* 设置缓存值并设置过期时间(自定义时间单位)
*/
@PostMapping("/setWithExpireUnit")
public String setWithExpireUnit(@RequestParam String key,
@RequestParam Long value,
@RequestParam long timeout) {
rString.setWithExpire(key, value, timeout, TimeUnit.DAYS);
return "Value set with custom expiration successfully!";
}
/**
* 设置缓存值,如果key不存在,则设置成功
*/
@PostMapping("/setIfAbsent")
public String setIfAbsent(@RequestParam String key,
@RequestParam Long value,
@RequestParam long timeout) {
boolean result = rString.setIfAbsent(key, value, timeout);
return result ? "Value set successfully!" : "Key already exists!";
}
/**
* 获取缓存值
*/
@GetMapping("/get")
public Long get(@RequestParam String key) {
return rString.get(key, Long.class);
}
/**
* 获取缓存值并设置新值
*/
@PostMapping("/getAndSet")
public Long getAndSet(@RequestParam String key, @RequestParam Long value) {
return rString.getAndSet(key, value, Long.class);
}
/**
* 根据 delta 值调整缓存中的数值
*/
@PostMapping("/changeByDelta")
public Long changeByDelta(@RequestParam String key, @RequestParam long delta) {
return rString.changeByDelta(key, delta);
}
}
5.RListController.java
java
package cn.sunxiansheng.redis.controller;
import cn.sunxiansheng.redis.utils.RList;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 测试 RList 工具类的 Controller
*
* @Author sun
* @Create 2024/11/14 16:00
* @Version 1.0
*/
@RestController
@RequestMapping("/rlist")
public class RListController {
@Autowired
private RList rList;
/**
* 左侧添加单个值
*/
@PostMapping("/leftPush")
public String leftPush(@RequestParam String key, @RequestBody User user) {
rList.leftPush(key, user);
return "User added to the left of the list.";
}
/**
* 左侧批量添加多个值
*/
@PostMapping("/leftPushAll")
public String leftPushAll(@RequestParam String key, @RequestBody List<User> users) {
rList.leftPushAll(key, users);
return "Users added to the left of the list.";
}
/**
* 右侧添加单个值
*/
@PostMapping("/rightPush")
public String rightPush(@RequestParam String key, @RequestBody User user) {
rList.rightPush(key, user);
return "User added to the right of the list.";
}
/**
* 右侧批量添加多个值
*/
@PostMapping("/rightPushAll")
public String rightPushAll(@RequestParam String key, @RequestBody List<User> users) {
rList.rightPushAll(key, users);
return "Users added to the right of the list.";
}
/**
* 根据索引设置List中的值
*/
@PutMapping("/set")
public String set(@RequestParam String key, @RequestParam int index, @RequestBody User user) {
rList.set(key, index, user);
return "User updated at index " + index;
}
/**
* 获取List中的所有数据
*/
@GetMapping("/rangeAll")
public List<User> rangeAll(@RequestParam String key) {
return rList.rangeAll(key, User.class);
}
/**
* 根据索引获取List中的元素
*/
@GetMapping("/getElementByIndex")
public User getElementByIndex(@RequestParam String key, @RequestParam int index) {
return rList.getElementByIndex(key, index, User.class);
}
/**
* 获取List的长度
*/
@GetMapping("/size")
public Long size(@RequestParam String key) {
return rList.size(key);
}
/**
* 从右侧弹出元素
*/
@DeleteMapping("/popRight")
public User popRight(@RequestParam String key) {
return rList.popRight(key, User.class);
}
/**
* 从左侧弹出元素
*/
@DeleteMapping("/popLeft")
public User popLeft(@RequestParam String key) {
return rList.popLeft(key, User.class);
}
/**
* 根据值移除指定数量的匹配元素
*/
@DeleteMapping("/removeByValue")
public String removeByValue(@RequestParam String key, @RequestParam int count, @RequestBody User user) {
Long removedCount = rList.removeByValue(key, count, user);
return removedCount + " matching users removed.";
}
}
/**
* 简单的自定义类型 User
*
* @Author sun
* @Create 2024/11/14 15:50
* @Version 1.0
*/
@NoArgsConstructor
@Data
@AllArgsConstructor
class User implements java.io.Serializable {
private String id;
private String name;
}
7.RedisApplication.java 启动类
java
package cn.sunxiansheng.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Description: RedisApplication
*
* @Author sun
* @Create 2025/1/19 19:33
* @Version 1.0
*/
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}