1、lua脚本decrby.lua
local current = redis.call('get', KEYS[1]);
if current == false then
return nil;
end
if tonumber(ARGV[1]) > tonumber(current) then
return redis.call('decrby', KEYS[1], current);
else
return redis.call('decrby', KEYS[1], ARGV[1]);
end
2、RedisLuaUtil.java
1)直接在代码中写lua脚本字符串
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* redis lua工具类
* @author xuzhipeng
* @date 2021/01/31
*/
@Component
public class RedisLuaUtil {
private static final Logger log = LoggerFactory.getLogger(RedisLuaUtil.class);
private static final String LUA_SCRIPT_DECRBY_UNTIL_TO_0 = "local current = redis.call('get', KEYS[1]);" +
"if current == false then " +
" return nil;" +
"end " +
"if tonumber(ARGV[1]) > tonumber(current) then " +
" return redis.call('decrby', KEYS[1], current);" +
"else " +
" return redis.call('decrby', KEYS[1], ARGV[1]);" +
"end";
@Resource
private RedisTemplate redisTemplate;
/**
* Decrby 命令将 key 所储存的值减去指定的减量值。(减至最小值为0)
* @param key
* @param delta
* @return 当key不存在时返回null;key存在,当前值<delta时,减去当前值;key存在,当前值>=delta时,减去delta;
*/
public Long decrByUntilTo0(String key, long delta){
List<String> keyList = new ArrayList<>();
keyList.add(key);
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(LUA_SCRIPT_DECRBY_UNTIL_TO_0,Long.class);
Long result = null;
try {
result = (Long) redisTemplate.execute(redisScript,keyList,delta);
} catch (Exception e) {
log.error("decrby异常",e);
}
return result;
}
}
2)引用lua脚本文件
/**
* Decrby 命令将 key 所储存的值减去指定的减量值。(减至最小值为0)
* @param key
* @param delta
* @return 当key不存在时返回null;key存在,当前值<delta时,减去当前值;key存在,当前值>=delta时,减去delta;
*/
public Long decrByUntilTo0(String key, long delta){
List<String> keyList = new ArrayList<>();
keyList.add(key);
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/decrby.lua")));
redisScript.setResultType(Long.class);
Long result = null;
try {
result = (Long) redisTemplate.execute(redisScript,keyList,delta);
} catch (Exception e) {
log.error("decrby异常",e);
}
return result;
}
网友评论