Lua表达式
在redis里面使用lua脚本主要用三个命令
eval
eval用来直接执行lua脚本,使用方式如下

- key代表要操作的rediskey
- arg可以传自定义的参数
- numkeys用来确定key有几个
- script就是你写的lua脚本
- lua脚本里面使用KEYS[1]和ARGV[1]来获取传递的key和arg
evalsha 和 script load
在用eval命令的时候,可以注意到每次都要把执行的脚本发送过去,这样势必会有一定的网络开销,所以redis对lua脚本做了缓存,通过script load 和 evalsha实现
script load命令会在redis服务器缓存你的lua脚本,并且返回脚本内容的SHA1校验和,然后通过evalsha 传递SHA1校验和来找到服务器缓存的脚本进行调用,这两个命令的格式以及使用方式如下

spring-data-redis操作lua
先导入依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.1.RELEASE</version>
</dependency>
然后我们使用StringRedisTemplate这个类来操作
@Resource
private StringRedisTemplate stringRedisTemplate;
public <T> T runLua(String fileClasspath, Class<T> returnType, List<String> keys, Object ... values){
DefaultRedisScript<T> redisScript =new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(fileClasspath)));
redisScript.setResultType(returnType);
return stringRedisTemplate.execute(redisScript,keys,values);
}
这个框架把lua脚本封装成RedisScript对象,并且可以将lua脚本执行的结果自动转换为配置的java类型,然后只要直接调用execute方法即可
并且这个execute逻辑中封装了evalsha的优化,源码如下
protected <T> T eval(RedisConnection connection, RedisScript<T> script, ReturnType returnType, int numKeys,
byte[][] keysAndArgs, RedisSerializer<T> resultSerializer) {
Object result;
try {
result = connection.evalSha(script.getSha1(), returnType, numKeys, keysAndArgs);
} catch (Exception e) {
if (!exceptionContainsNoScriptError(e)) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RedisSystemException(e.getMessage(), e);
}
result = connection.eval(scriptBytes(script), returnType, numKeys, keysAndArgs);
}
if (script.getResultType() == null) {
return null;
}
return deserializeResult(resultSerializer, result);
}
lua Debug
在运行lua的eval,加上-ldb即可开启debug功能,debug只支持eval命令
./redis-cli --ldb --eval /tmp/script.lua mykey somekey , arg1 arg2
然后提供了一些调试命令
lua debugger> help
Redis Lua debugger help:
[h]elp Show this help.
[s]tep Run current line and stop again.
[n]ext Alias for step.
[c]continue Run till next breakpoint.
[l]list List source code around current line.
[l]list [line] List source code around [line].
line = 0 means: current position.
[l]list [line] [ctx] In this form [ctx] specifies how many lines
to show before/after [line].
[w]hole List all source code. Alias for 'list 1 1000000'.
[p]rint Show all the local variables.
[p]rint <var> Show the value of the specified variable.
Can also show global vars KEYS and ARGV.
[b]reak Show all breakpoints.
[b]reak <line> Add a breakpoint to the specified line.
[b]reak -<line> Remove breakpoint from the specified line.
[b]reak 0 Remove all breakpoints.
[t]race Show a backtrace.
[e]eval <code> Execute some Lua code (in a different callframe).
[r]edis <cmd> Execute a Redis command.
[m]axlen [len] Trim logged Redis replies and Lua var dumps to len.
Specifying zero as <len> means unlimited.
[a]abort Stop the execution of the script. In sync
mode dataset changes will be retained.
Debugger functions you can call from Lua scripts:
redis.debug() Produce logs in the debugger console.
redis.breakpoint() Stop execution as if there was a breakpoint in the
next line of code.
用redis.debug() 可以打日志
用redis.breakpoint()在lua脚本里打断点
s和n都是跳到下行代码
c是跳到下个断点
list可以展示当前这条代码前后的代码
写个简单的lua脚本来测试下
local value1 = ARGV[1]
local value2 = ARGV[2]
redis.debug(value1)
redis.debug(value2)
if(value1>value2)
then
return "a"
else
return "b"
end
项目实战
新建一个lua脚本
local key = KEYS[1]
local id = redis.call('get',key)
if(id == false)
then
redis.call('set',key,1)
return key.."0001"
else
redis.call('set',key,id+1)
return key..string.format('%04d',id + 1)
end
对应调用java代码如下
public String nextIDLua(){
String key = Prefix+simpleDateFormatThreadLocal.get().format(new Date());
DefaultRedisScript<String> redisScript =new DefaultRedisScript<>();
redisScript.setLocation(new ClassPathResource("lua/genID.lua"));
redisScript.setResultType(String.class);
//System.out.println(redisScript.getSha1());
return redisTemplate.execute(redisScript,(RedisSerializer<?>) redisTemplate.getKeySerializer(),(RedisSerializer<String>)redisTemplate.getKeySerializer(),Lists.newArrayList(key));
}
一些基本的语法
boolean(布尔)
boolean 类型只有两个可选值:true(真) 和 false(假),Lua 把 false 和 nil 看作是"假",其他的都为"真":
print(type(true))
print(type(false))
print(type(nil))
if false or nil then
print("至少有一个是 true")
else
print("false 和 nil 都为 false!")
end
以上代码执行结果如下:
$ lua test.lua
boolean
boolean
nil
false 和 nil 都为 false!
或者
if false or nil or 1 then
print("至少有一个是 true")
else
print("false 和 nil 都为 false!")
end
以上代码执行结果如下:
boolean
boolean
nil
至少有一个是 true
字符串
字符串由一对双引号或单引号来表示。
string1 = "this is string1"
string2 = 'this is string2'
也可以用 2 个方括号 "[[]]" 来表示"一块"字符串。
html = [[
<html>
<head></head>
<body>
<a href="http://www.runoob.com/">菜鸟教程</a>
</body>
</html>
]]
print(html)
以下代码执行结果为:
<html>
<head></head>
<body>
<a href="http://www.runoob.com/">xxx教程</a>
</body>
</html>
table(表)
在 Lua 里,table 的创建是通过"构造表达式"来完成,最简单构造表达式是{},用来创建一个空表。也可以在表里添加一些数据,直接初始化表:
-- 创建一个空的 table
local tbl1 = {}
-- 直接初始表
local tbl2 = {"apple", "pear", "orange", "grape"}
Lua 中的表(table)其实是一个"关联数组"(associative arrays),数组的索引可以是数字或者是字符串。
-- table_test.lua 脚本文件
a = {}
a["key"] = "value"
key = 10
a[key] = 22
a[key] = a[key] + 11
for k, v in pairs(a) do
print(k .. " : " .. v)
end
脚本的执行结果:
$ lua table_test.lua
key : value
10 : 33
不同于其他语言的数组把 0 作为数组的初始索引,在 Lua 里表的默认初始索引一般以 1 开始。
-- table_test2.lua 脚本文件
local tbl = {"apple", "pear", "orange", "grape"}
for key, val in pairs(tbl) do
print("Key", key)
end
脚本的执行结果:
$ lua table_test2.lua
Key 1
Key 2
Key 3
Key 4
table 不会固定长度大小,有新数据添加时 table 长度会自动增长,没初始的 table 都是 nil。
function(函数)
在 Lua 中,函数是被看作是"第一类值(First-Class Value)",函数可以存在变量里:
-- function_test.lua 脚本文件
function factorial1(n)
if n == 0 then
return 1
else
return n * factorial1(n - 1)
end
end
print(factorial1(5))
factorial2 = factorial1
print(factorial2(5))
脚本执行结果为:
$ lua function_test.lua
120
120
function 可以以匿名函数(anonymous function)的方式通过参数传递:
-- function_test2.lua 脚本文件
function testFun(tab,fun)
for k ,v in pairs(tab) do
print(fun(k,v));
end
end
tab={key1="val1",key2="val2"};
testFun(tab,
function(key,val)--匿名函数
return key.."="..val;
end
);
脚本的执行结果:
$ lua function_test2.lua
key1 = val1
key2 = val2
变量
-- test.lua 文件脚本
a = 5 -- 全局变量
local b = 5 -- 局部变量
function joke()
c = 5 -- 全局变量
local d = 6 -- 局部变量
end
joke()
print(c,d) --> 5 nil
do
local a = 6 -- 局部变量
b = 6 -- 对局部变量重新赋值
print(a,b); --> 6 6
end
print(a,b) --> 5 6
赋值语句
a = "hello" .. "world"
t.n = t.n + 1
Lua 可以对多个变量同时赋值,变量列表和值列表的各个元素用逗号分开,赋值语句右边的值会依次赋给左边的变量。
a, b = 10, 2*x <--> a=10; b=2*x
遇到赋值语句Lua会先计算右边所有的值然后再执行赋值操作,所以我们可以这样进行交换变量的值:
x, y = y, x -- swap 'x' for 'y'
a[i], a[j] = a[j], a[i] -- swap 'a[i]' for 'a[j]'
当变量个数和值的个数不一致时,Lua会一直以变量个数为基础采取以下策略:
a. 变量个数 > 值的个数 按变量个数补足nil
b. 变量个数 < 值的个数 多余的值会被忽略
a, b, c = 0, 1
print(a,b,c) --> 0 1 nil
a, b = a+1, b+1, b+2 -- value of b+2 is ignored
print(a,b) --> 1 2
a, b, c = 0
print(a,b,c) --> 0 nil nil
上面最后一个例子是一个常见的错误情况,注意:如果要对多个变量赋值必须依次对每个变量赋值。
a, b, c = 0, 0, 0
print(a,b,c) --> 0 0 0
索引
对 table 的索引使用方括号 []。Lua 也提供了 . 操作。
t[i]
t.i -- 当索引为字符串类型时的一种简化写法
gettable_event(t,i) -- 采用索引访问本质上是一个类似这样的函数调用
循环
在循环体中如果条件永远为 true 循环语句就会永远执行下去,以下以 while 循环为例:
while( true )
do
print("循环将永远执行下去")
end
Lua 编程语言中数值for循环语法格式:
for var=exp1,exp2,exp3 do
<执行体>
end
for的三个表达式在循环开始前一次性求值,以后不再进行求值。比如上面的f(x)只会在循环开始前执行一次,其结果用在后面的循环中。
function f(x)
print("function")
return x*2
end
for i=1,f(5) do print(i)
end
以上实例输出结果为:
1
2
3
4
5
6
7
8
9
10

浙公网安备 33010602011771号