引用自:http://geek.csdn.net/news/detail/246932
Redis作用: 限流库存扣减异步下单

1
2
3
4
"goodsId" : {
"Total": 100
"Booked": 100
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
local n = tonumber(ARGV[1])
if not n or n == 0 then
return 0
end
local vals = redis.call("HMGET", KEYS[1], "Total", "Booked");
local total = tonumber(vals[1])
local blocked = tonumber(vals[2])
if not total or not blocked then
return 0
end
if blocked + n <= total then
redis.call("HINCRBY", KEYS[1], "Booked", n)
return n;
end
return 0

先使用SCRIPT LOAD将lua脚本提前缓存在Redis,然后调用EVALSHA调用脚本,比直接调用EVAL节省网络带宽:
redis 127.0.0.1:6379>SCRIPT LOAD “lua code”
“438dd755f3fe0d32771753eb57f075b18fed7716”

redis 127.0.0.1:6379>EVAL 438dd755f3fe0d32771753eb57f075b18fed7716 1 goodsId 1

1
2
3
4
5
6
7
> orderList {
[0] = {订单内容}
[1] = {订单内容}
[2] = {订单内容}
...
}
>

LPUSH orderList {订单内容}

异步下单模块从Redis中顺序获取订单信息,并将订单写入数据库:

BRPOP orderList 0