mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-22 15:13:55 +08:00
新增获取在redis指定key的值,如果值为空,着设置key的默认值的方法
--RedisUtils.java 添加新方法 --getKeyOrCreate.lua 此方法的lua脚本
This commit is contained in:
@@ -6,12 +6,14 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.HashOperations;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import xiaozhi.common.utils.ResourcesUtils;
|
||||
|
||||
/**
|
||||
* Redis工具类
|
||||
@@ -23,6 +25,9 @@ public class RedisUtils {
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
@Autowired
|
||||
private ResourcesUtils resourceUtils;
|
||||
|
||||
/**
|
||||
* 默认过期时长为24小时,单位:秒
|
||||
*/
|
||||
@@ -147,4 +152,26 @@ public class RedisUtils {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取在redis指定key的值,如果值为空,着设置key的默认值
|
||||
* @param key redis的key
|
||||
* @param defaultValue 默认值
|
||||
* @param expiresInSecond 过期时间
|
||||
* @return 返回key的值
|
||||
*/
|
||||
public String getKeyOrCreate(String key, String defaultValue,Long expiresInSecond) {
|
||||
// Lua 脚本
|
||||
String luaScript = resourceUtils.loadString("lua/getKeyOrCreate.lua");
|
||||
|
||||
DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
|
||||
redisScript.setScriptText(luaScript);
|
||||
redisScript.setResultType(String.class);
|
||||
|
||||
// 执行 Lua 脚本
|
||||
List<String> keys = Collections.singletonList(key);
|
||||
return redisTemplate.execute(redisScript, keys, defaultValue,expiresInSecond);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
local value = redis.call('GET', KEYS[1])
|
||||
-- value 如果为空着设置值
|
||||
if not value then
|
||||
local result = redis.call('SET', KEYS[1], ARGV[1])
|
||||
-- 检查 ARGV[2] 是否存在且大于 0
|
||||
local expireTime = tonumber(ARGV[2])
|
||||
if expireTime and expireTime > 0 then
|
||||
redis.call('EXPIRE', KEYS[1], expireTime)
|
||||
end
|
||||
end
|
||||
return value
|
||||
Reference in New Issue
Block a user