26 redis-lua表达式怎么写?代码里写lua脚本有啥优缺点?

vvEcho 2026-01-17 12:23:24
Categories: Tags:

一般java后端这么写
扣减库存的lua脚步:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
String script =
"local stock = redis.call('GET', KEYS[1]) " +
"if not stock then return -2 end " +
"stock = tonumber(stock) " +
"local deduct = tonumber(ARGV[1]) " +
"if stock < deduct then return -1 end " +
"redis.call('DECRBY', KEYS[1], deduct) " +
"return stock - deduct";

Long result = redisTemplate.execute(
new DefaultRedisScript<>(script, Long.class),
Collections.singletonList("product:stock:1001"),
"1"
);

if (result >= 0) {
// 成功,下单
} else if (result == -1) {
// 库存不足
} else {
// 库存不存在
}

Redis Lua 脚本通过 KEYS 和 ARGV 传参,在 Redis 主线程中原子执行
优点是原子性强、可写复杂逻辑、减少网络开销
缺点是会阻塞主线程、调试困难、集群下有 slot 限制
一般用于限流、扣库存、幂等等高并发原子场景