lua脚本
resources 下创建文件 redis/AccessLimit.lua
内容为:
local limitSecond = tonumber(ARGV[1])
local limitMaxCount = tonumber(ARGV[2])
local num = tonumber(redis.call('get', KEYS[1]) or '-1')
if num == -1 then
redis.call('incr', KEYS[1])
redis.call('expire', KEYS[1], limitSecond)
return 1
else
if num >= limitMaxCount then
return 0
else
redis.call('incr', KEYS[1])
return 1
end
end
API测试
@RestController
public class TestController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("test")
public String test() {
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis/AccessLimit.lua")));
redisScript.setResultType(Long.class);
Long result = stringRedisTemplate.execute(redisScript, Arrays.asList("user1"), "5", "10");
return result+"";
}
}
注意事项
- 必须使用lua脚本保证原子性
- 参数使用字符串生效